I have to pass a UITextField value from one view to other views(2nd,3rd...views).Actually in my 3rd ViewController I have a scrollView and I have to display value on it .But UIT
I am just correcting the code you have written meanwhile the suggestions given above for using AppDelegate property is a good one. The main problem with your code is that you are just declaring NSString object instead of making it a property. Check this:
-(IBAction)butonclick:(id)sender{
ViewController2 *view2=[ViewController2 alloc]init];
view2.str=name.text;
ViewController3 *view3=[ViewController3 alloc]init;
view3.str=name.text;
[view2 release];
[view3 release];
}
IN ViewConroller2.h :
@interface ViewController2 : UIViewController {
NSString *str;
UIlabel *displayId;
}
@property(nonatomic, retain) NSString* str; //Synthesize it in .m file
In ViewController2.m :
- (void)viewDidLoad
{
self.displayId.text=self.str;
}
In ViewController3.h:
@interface ViewController2 : UIViewController {
NSString *str;
UIlabel *dispId;
}
@property(nonatomic, retain) NSString* str; //Synthesize it in .m file
In ViewController3.m :
- (void)viewDidLoad
{
self.dispId.text=self.str;
}
I am not aware with your scenario but the most effective way of implementing such situations is using Delegates. Make a delegate of the class where your string is being set (ViewController1) and set delegate accordingly in your other view controllers.
You are passing the values without initializing.
ViewController2 *view2=[[ViewController2 alloc]init];
view2.id=name.text;
ViewController3 *view3=[[ViewController3 alloc]init];
view3.id=name.text;
If you want to use object globally within your app, you can declare it in the appDelegate.
In AppDelegate.h
@interface AppDelegate : NSObject <NSApplicationDelegate>
{
NSString *idGlobal;
}
@property (nonatomic, retain) NSString *idGlobal;
In AppDelegate.m
@synthesize idGlobal;
In ViewController1.m:
-(IBAction)butonclick:(id)sender{
appDelegate.idGlobal=name.text;
}
In ViewController2.m: and
In ViewController3.m:
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
id=appDelegate.idGlobal;
Declare the string globally in the AppDelegate.h
this will help in keeping the value of the string constant throughout the files. Also wherever you want to add the string or change its value or assign it import the AppDelegate.h
.
Also check these links :-
passing NSString from one class to the other
Pass NSString from one class to another