I have some class initialized in Appdelegate, but when I get this class instance form Appdelegate in another class it has "fresh" state.
I have following in AppDelegate:
Interface:
@property (nonatomic, retain) DataController *dataController;
Implementation:
@synthesize dataController;
- (id)init {
if (self = [super init]) {
DataController *controller = [[DataController alloc] init];
self.dataController = controller;
[controller release];
NSLog(@"items: %d",[self.dataController numberOfItems]);
}
return self;
}
At this point DataControlelr class loads objects form database. Log output show "items: 10".
I have TableViewController where I need to use DataController.
TableViewController header:
@interface TableViewController : UITableViewController {
DataController *dataController;
}
@property (retain) DataController *dataController;
@end
Implementation:
-(id)init{
if (self =[super init]) {
DataController *dc =[(AppDelegate *)[[UIApplication sharedApplication] delegate] dataController];
[dc retain];
dataController = dc;
NSLog(@"items: %d",[self.dataController numberOfItems]);
}
return self;
}
Here it always says that DataController has 0 items. "fresh" state.
The Log output is always
items: 10
items: 0
It seems like assigning that class creates reference to freshly initialised DataController somehow?
How do I reference another class properly?
Thanks.
The first thing to check would be to ensure that the
dcvariable in the second class isn’t nil– that would cause any method called on it to ‘return’ 0.It might also be useful to print out the address of the app delegate from both of those methods– just in case the
-initmethod is resulting from an incorrectly-allocated second instance of that class somewhere, while the regular version hasn’t been initialized in the same way (or was using-initWithCoder:, etc.)One useful rule of thumb for initialization of objects created or assigned within a nib file is to use
-awakeFromNibto perform most of your initialization tasks. A corollary to this is that the app delegate can set up its state in response to the-applicationDidFinishLaunching:method. In this case, if there is a second instance of your AppDelegate class being allocated somewhere, only the one which is really set as the app’s delegate will receive-applicationDidFinishLaunching:.At the end of the day, stepping through in the debugger and looking at the call stack should show you if something isn’t happening in quite the way it should.