简体   繁体   中英

In objective-C (ios) ,Has anybody used singleton instance?

从单例实例的内存角度来看,我们如何删除创建的单例实例,因为它已被放入自动释放池中?

Singleton instance shouldn't be placed in autorelease pool. Singleton instance should be created once (usually when first referenced) and deleted when the application terminates (I mean automatically by iOS). This is why singleton is usually assigned to a static variable.

You should increase the reference counter (retain) the singleton instance when assigning to that static variable. At that point even if you add it to an autorelease pool it won't be deleted as it is already retained somewhere else.

To delete that singleton instance you would simply need to release the current object assigned to the static variable (eg release) and assign nil or create a new singleton. If the same instance has been added to an autorelease pool it won't be deleted immediately, only after that autorelease pool has been deleted itself. But it shouldn't change much in your application as the singleton is already nil or recreated as a new instance, thus any further calls will retrieve the new instance.

Again, I don't see any reason why you would add a singleton to autorelease pool. Please share a snippet of code if this doesn't answer your question.

There's some debate on how to create a singleton. I use the following pattern:

+ (MYSingletonClass *) sharedInstance
{
    static dispatch_once_t onceToken;
    static MYSingletonClass * __sharedInstance = nil;

    dispatch_once(&onceToken, ^{
        __sharedInstance = [[self alloc] init];
    });

    return __sharedInstance;
}

On clarification by the OP, it turns out this doesn't answer the question, but I thought I'd share anyway :)

See the this post comparing @synchronized v dispatch_once

As far as I know, Singletons are helpful because you do NOT release them until your app is closed. So your data are always available.

If you need to free memory I suggest you find a different way to menage data...

static id sharedInstance=nil;

+(id)sharedInstance 
{
    @synchronized(self) 
    {
        if(!sharedInstance)
       {
           NSLog(@"Allocated");
           sharedInstance = [[self alloc] init];
       }
   }
   return sharedInstance;
}
//standard way to declare singleton object

如果您需要清除其内容,也许可以向您的单例对象添加“清除”方法...

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM