I'm using the common singleton pattern as follows:
+ (SomeClass *)sharedInstance {
static SomeClass *__sharedInstance;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
__sharedInstance = [[SomeClass alloc] init];
});
return __sharedInstance;
}
I understand that the SomeClass object gets instantiated the first time I call [SomeClass sharedInstance], however, when does SomeClass get dealloc'd?
This is under ARC so when does the compiler release the SomeClass static object? Is it guaranteed to be around for the rest of the life of my app?
Since the declaration of __sharedInstance
is inside sharedInstance
's scope, it cannot be accessed directly by any other methods. This means that no one else can set it to nil
, and therefore it will be kept until your app will be terminated.
It's also worth mentioning that you cannot be certain that the dealloc
method of your singleton will be called when the system frees your memory on termination, mainly because:
dealloc
method before that happens. dealloc
method, then you cannot predict the order of object destruction while terminating (such as frameworks that you use), making your code unreliable.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.