问题描述
如何在Objective C中创建单例类?
How can I create a singleton class in Objective C?
推荐答案
好的appDev,你可能会发现很多不同的在网上做这个的技巧。但是,对于iOS应用程序开发,我认为最方便的方法是执行以下操作:
Okay appDev, you will probably find quite a few different techniques to do this on the web. However, for iOS app development, I think the most convenient way is to do the following:
-
编写您的方法获取单例对象。 (建议:使用
dispatch_once
thread和GCD)。
Write your method(s) for getting the singleton object. (Recommendation: use
dispatch_once
thread and GCD for this).
将您的方法包装在宏中并将其添加到 $ Project $ -Prefix.pch
file。
Wrap your method(s) in a macro and add it to your $Project$-Prefix.pch
file.
只要你需要一个类的单例对象,就调用一行宏。
Call the one line macro whenever you need singleton object for a class.
示例:
CommonMacros.h :
#define SINGLETON_FOR_CLASS(classname)
+ (id) shared##classname {
static dispatch_once_t pred = 0;
static id _sharedObject = nil;
dispatch_once(&pred, ^{
_sharedObject = [[self alloc] init];
});
return _sharedObject;
}
YourProject-Prefix.pch:
...
#import "CommonMacros.h"
...
YourSingletonClass.m:
...
SINGLETON_FOR_CLASS(YourSingletonClass)
...
这篇关于如何在目标C中创建单例类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!