ios – 可能设置单身回到零吗?

ios – 可能设置单身回到零吗?,第1张

概述我已经使用常规模式实现了一个单例对象.我的问题是:是否可以将此对象设置为nil,以便稍后调用[MySingleton sharedInstance]对象将被重新初始化? // Get the shared instance and create it if necessary.+ (MySingleton *)sharedInstance { static dispatch_once_ 我已经使用常规模式实现了一个单例对象.我的问题是:是否可以将此对象设置为nil,以便稍后调用[MySingleton sharedInstance]对象将被重新初始化?
// Get the shared instance and create it if necessary.+ (MySingleton *)sharedInstance {    static dispatch_once_t pred;    static MySingleton *shared = nil;    dispatch_once(&pred,^{        shared = [[MySingleton alloc] init];    });    return shared;}// We can still have a regular init method,that will get called the first time the     Singleton is used.- (ID)init {    self = [super init];    if (self) {    // Work your initialising magic here as you normally would    }    return self;}

我的猜测是这样的

MySingleton *shared = [MySingleton sharedInstance];shared = nil;

只将本地指针共享为nil.毕竟,共享被声明为静态的.

解决方法 你对本地参考的假设是正确的,它不会影响你的单身人士.

为了能够重新初始化单例,您需要将静态变量从你的方法中移出,所以它可以被整个类访问.

static MySingleton *sharedInstance = nil;// Get the shared instance and create it if necessary.+ (MySingleton *)sharedInstance {    if (sharedInstance == nil) {        sharedInstance = [[MySingleton alloc] init];    }    return sharedInstance;}+ (voID)resetSharedInstance {    sharedInstance = nil;}

请注意,您不能再使用dispatch_once,因为您的单身明显需要多次创建.如果你只是从你的UI中调用这个单例(因此只从主线程),那么上面的示例是正确的.

如果您需要从多个线程进行访问,则需要对sharedInstance和resetSharedInstance方法进行锁定.

+ (ID)sharedInstance {    @synchronized(self) {        if (sharedInstance == nil) {            sharedInstance = [[MySingleton alloc] init];        }        return sharedInstance;    }}+ (voID)resetSharedInstance {    @synchronized(self) {        sharedInstance = nil;    }}

这比dispatch_once变体有点慢,但实际上通常并不重要.

总结

以上是内存溢出为你收集整理的ios – 可能设置单身回到零吗?全部内容,希望文章能够帮你解决ios – 可能设置单身回到零吗?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1111372.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-29
下一篇 2022-05-29

发表评论

登录后才能评论

评论列表(0条)

保存