I want to use global variables in my code. I have some ViewController that use some instances, so use global will be easier then pass instances between controllers.
Thus, I create the global in AppDelegate:
AppDelegate.h
@interface AppDelegate : UIResponder <UIApplicationDelegate>{
//Global Variables
NSInteger userID;
NSMutableArray *friends;
}
@property (assign, nonatomic) NSInteger userID;
@property (strong, nonatomic) NSMutableArray *friends;
AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
...
self.friends = [[NSMutableArray alloc] init];
return YES;
}
And I access global in any controller adding this code in ViewControllerN.h:
#import "AppDelegate.h"
#define global \ ((AppDelegate *)[UIApplication sharedApplication].delegate)
So in ViewControllerN.m I can access global, for example:
[global.friends addObject:@"Henry"];
It works perfectly. But in somewhere, I am losing data from global.
I start my app in PageControllerA (ControllerA)
- Controller A have a scrollView with ControllerB,C and D.
- I add data to global.friend in ControllerA viewdidLoad
- Controller B,C,D can access global correctly in viewDidLoad, but when I call a method from any of this controllers global.friend is Empty.
- Controller B call Controller E but global.friend is empty for Controller E too.
I only white data in global.friend, never remove any objects.
Why I am losing data? (global.friend empty)