My method + (void) initialized is not called and I’m very new in Objective C. The code is in the book iPhone Game Development and I have to call the method explicitly to work. The code in the .m file is that:
ResourceManager *g_ResManager;
@implementation ResourceManager
//initialize is called automatically before the class gets any other message, per from http://stackoverflow.com/questions/145154/what-does-your-objective-c-singleton-look-like
+ (void) initialize
{
static BOOL initialized = NO;
if(!initialized)
{
initialized = YES;
g_ResManager = [[ResourceManager alloc] init];
}
}
...
@end
But in the .h file a external declaration of the variable is made:
extern ResourceManager *g_ResManager; //paul <3's camel caps, hungarian notation, and underscores.
@interface ResourceManager : NSObject {
...
}
...
@end
I tried everything (remove the external, put static in the .m declaration) and always get compilation errors. The code above compiles but the method initialize is never called (putted a breakpoint to see that).
Some clue?
+initializeis not called until you send some message to an instance of the class. Did you send a message?One possible problem might be that you sent a message to
g_ResManagerfrom another portion of your code?That won’t work, because:
g_ResManageris nil at the launch time.g_ResManager, which isnil.nilgets the message,nilis not an instance ofResourceManager, so+initializeis not called either.I would change your code as follows: first, in .m,
and then in .h, I would just have
Then, you can always use
[ResourceManager sharedResourceManager].In fact, as Rob says in the comment, you can totally do away with
+initializein this case. Change .m to something likeThis is the idiom I always use personally. But I warn you this is not completely thread safe! It should be OK as long as you call
[ResourceManager sharedResourceManager]once before spawning threads, which I would almost always do anyway, but that’s one thing to keep in mind. On the other hand, the version above using+initializeshould be thread safe as is, thanks to the well-defined behavior of+initialize. See discussions in this blog post.