nitinsh99 nitinsh99 - 6 months ago 19
Objective-C Question

iOS Appdelagate field population and object creation

I am new to iOS and was trying to wrap my head around the functionality of Appdelegate callback's and field population.

So here's what I am doing:
declaring a global property in Appdelegate's header

@property NSString* GlobalUsername;

Populating the value to this property in one on of the callbacks

- (void)applicationDidBecomeActive:(UIApplication *)application {

_GlobalUsername = @"username";


Now in the ViewControler's button click method, I am creating an object of AppDelegate, accessing GlobalUsername and showing it on the screen using textView.

- (IBAction)ShowDetails:(id)sender
AppDelegate *appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;

NSString* details=[NSString stringWithFormat:@"Username is : %@",appdelegate.GlobalUsername];
[_textView setText:details];


Now what I don't understand is that how is the value of GlobalUsername is being associated with the object of AppDelegate. GlobalUsername was populated when application became active and not when I created an instance of the Appdelegate so how does the object returned by sharedApplication method still has this information encapsulated with it?

Thanks in advance and hope I am making sense.


delegate of UIApplication works according to singleton pattern. There is only 1 instance every time you try to get it. For example:

[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
...Any API requests...
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];

If UIApplication's delegate will be different every time it won't save state of network indicator.