Reputation: 391
In AppDelegate.h
@property(strong,nonatomic)NSString *str2;
In ViewController.m
AppDelegate *c3=[[AppDelegate alloc]init];
c3.str2= @"Hello";
NSLog(@"Output:-%@",c3.str2);
Output:-Hello
Navigation code in Tableview didselect method(view Controller):-
Class2 *c2=[self.storyboard instantiateViewControllerWithIdentifier:@"cl2"];
[self.navigationController pushViewController:c2 animated:YES];
In Class2.m:-
AppDelegate *c3=[[AppDelegate alloc]init];
NSLog(@"%@",c3.str2);
Output:-Null
Upvotes: 0
Views: 71
Reputation: 40038
In AppDelegate.h
@property(strong,nonatomic) NSString *str2;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
_str2 = "Hello"
}
In ViewController.m
and any other view controller that wants to access str2
:
AppDelegate *delegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
NSLog(@"Output: %@", delegate.str2);
Never create AppDelegate
object on your own. Instead, access its instance via sharedApplication
.
Upvotes: 2
Reputation: 727047
First, let's fix your current approach: the reason some recommend using app delegate to store shared values is that there is one easily accessible instance of it. You never create a new app delegate, but access the shared one instead:
AppDelegate *c3 = (AppDelegate*)[[UIApplication sharedApplication] delegate];
Once you replace [[AppDelegate alloc]init]
with the above, your code will start working the way you expect.
However, this solution is not ideal. App delegate is not supposed to be a place for storing shared values; they should be stored in your model object (as "M" in MVC, Model-View-Controller). Create a singleton model object, place shared variable in it, and use that shared variable by accessing the singleton from different view controllers.
Upvotes: 5