It\'s a classic problem.
I would like to access an array of objects from anywhere within my app. I would also like to do this using a singleton. My questions are:
Do your singleton like this:
@interface Singleton : NSObject
@property (nonatomic, retain) NSMutableArray *bananas;
+(Singleton*)singleton;
@end
@implementation Singleton
@synthesize bananas;
+(Singleton *)singleton {
static dispatch_once_t pred;
static Singleton *shared = nil;
dispatch_once(&pred, ^{
shared = [[Singleton alloc] init];
shared.bananas = [[NSMutableArray alloc]init];
});
return shared;
}
@end
The singleton is initialized the first time you use it. You can call it from anywhere at any time:
NSLog(@"%@",[Singleton singleton].bananas);
You use lazy instantiation, that is, a class method that returns your singleton object. The first time this method is called, it creates the instance, all other times thereafter, it just returns the already available instance (retained in a class variable).
I thought the point of your singleton was to hold this array? You could either create it in the singleton's initializer, or create it lazily when it is needed the first time.
In your AppName-pefix.pch file, you #import its class. This global import will be available in your whole application.