开发者

Singleton Safety with +(void)load

I've just been looking at the header files for NSObject, and I'm creating a singleton class. The problem I have is that it needs to load up basically from the start of the application, as the singleton maintains state for the application by observing NSNotifications and reporting the current state when asked.

My solution to this was to use the +(void)load method on NSObject. When the class loads into memory, I was going to override the load method, and allocate the singleton at that stage.

The documentation from Apple does not make it clear if it is safe to call [[*class* alloc] init] during the load method. I would generally assume it was, unless it was documented, but considering the i开发者_如何学运维mportance of this item, and the fact that I'm loading this every time the app launches, I'd like to know anyone has any knowledge of whether this is safe or not, just for reassurance.

Many thanks for any assistance.


It depends on what exactly your class (and its superclasses) does when you call init. During load, other classes are not guaranteed to be available. If your class's init doesn't need any other classes, you might be able to get away with it.

It would be much safer to do this in + (void)initialize instead, and if necessary to call a setup function during application launch (e.g. from application:didFinishLaunchingWithOptions: on iOS).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜