Hi ambush -
What you described makes sense, but I'm not 100% clear on this.
Basically, say I want a MyObject that I can access from anywhere in my app. From what I understand, this is what I'd do - and please correct me if/where I'm wrong:
in MyObject.h, I declare a class method:
Code:
+ (MyObject *)sharedObject;
in MyObject.m, I implement the above method as follows:
Code:
+ (MyObject *)sharedObject
{
static id sharedInstance = nil;
if ( sharedInstance == nil )
{
sharedInstance = [[self alloc] init];
}
return sharedInstance;
}
And finally, from anywhere in my codebase where myObject.h has been #import-ed, I can retrieve this persistent instance into a variable by sending a message like:
Code:
theSharedInstance = [MyObject sharedObject];
- and it will retrieve the same instance no matter where or when I call it (or create it if it hasn't been called for yet).
Is that right? That seems very clever and elegant to me! Much better than a random global variable, to be sure. Is this how things like [NSUserDefaults standardUserDefaults] work?
Also, I suppose that I needn't ever retain or release this object until the application is about to exit - how do I handle releasing it at that point (or should I not worry b/c the memory will be released anyway when the app exits)?
Thank you for taking the time to explain this!
-N