我的 Objective

编程入门 行业动态 更新时间:2024-10-22 17:17:34
本文介绍了我的 Objective-C 单例应该是什么样的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的单例访问器方法通常是以下的一些变体:

My singleton accessor method is usually some variant of:

static MyClass *gInstance = NULL; + (MyClass *)instance { @synchronized(self) { if (gInstance == NULL) gInstance = [[self alloc] init]; } return(gInstance); }

我可以做些什么来改善这一点?

What could I be doing to improve this?

推荐答案

另一种选择是使用 +(void)initialize 方法.来自文档:

Another option is to use the +(void)initialize method. From the documentation:

运行时将 initialize 发送到程序中的每个类,恰好在该类或从它继承的任何类从程序内部发送其第一条消息之前.(因此,如果不使用该类,则该方法可能永远不会被调用.)运行时以线程安全的方式向类发送 initialize 消息.超类在其子类之前收到此消息.

The runtime sends initialize to each class in a program exactly one time just before the class, or any class that inherits from it, is sent its first message from within the program. (Thus the method may never be invoked if the class is not used.) The runtime sends the initialize message to classes in a thread-safe manner. Superclasses receive this message before their subclasses.

所以你可以做一些类似的事情:

So you could do something akin to this:

static MySingleton *sharedSingleton; + (void)initialize { static BOOL initialized = NO; if(!initialized) { initialized = YES; sharedSingleton = [[MySingleton alloc] init]; } }

更多推荐

我的 Objective

本文发布于:2023-11-01 17:59:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1550016.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Objective

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!