nitinsh99 nitinsh99 - 1 year ago 55
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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download