Working off an idea from the Big Nerd Ranch guide to iOS programming, I’m trying to define singleton object in the following manner:
@implementation ImageStore
static ImageStore *defaultImageStore = nil;
- (id)init
{
if (defaultImageStore) {
return defaultImageStore;
}
self = [super init];
if (self) {
dictionary = [[NSMutableDictionary alloc] init];
}
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter addObserver:self selector:@selector(clearCache) name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
return self;
}
+ (id)allocWithZone:(NSZone *)zone
{
return [self defaultImageStore];
}
+ (ImageStore *)defaultImageStore
{
if (!defaultImageStore) {
defaultImageStore = [[super allocWithZone:NULL] init];
}
return defaultImageStore;
}
This works fine, but the analyzer complains about allocWithZone, saying
Object with +0 retain counts returned to caller where a +1 (owning) retain count is expected
I think the code is just tricking the analyzer and that what’s happening is OK, but is there a better model to do what I’m trying to do?
I don’t bother with all that stuff. This is my pattern:
@implementation MyClass
Possbily you can hide the initialiser in a class extension so that it is documented that you shouldn’t use it.
There’s also the GCD method (the below is stolen from Rob Napier’s link) which is actually more lightweight.
I’ve always resisted the GCD pattern because to my eye it looks less obvious what is happening. However, that’s nothing that can’t be fixed with a comment! The locks used by GCD are more lightweight in comparison to @synchronized, so this will be faster.