Rya*_*yan 341 singleton objective-c grand-central-dispatch ios
如果您可以定位iOS 4.0或更高版本
使用GCD,它是在Objective C(线程安全)中创建单例的最佳方法吗?
+ (instancetype)sharedInstance
{
static dispatch_once_t once;
static id sharedInstance;
dispatch_once(&once, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}
Run Code Online (Sandbox Code Playgroud)
Dav*_*ong 215
这是创建类实例的完全可接受且线程安全的方法.它在技术上可能不是"单例"(因为它们只能有1个这样的对象),但只要你只使用该[Foo sharedFoo]方法来访问对象,这就足够了.
Zel*_*lko 36
instancetype只是众多语言扩展中的一种Objective-C,每个新版本都添加了更多.
知道它,喜欢它.
并将其作为一个例子,说明如何关注低级细节可以让您深入了解改变Objective-C的强大新方法.
+ (instancetype)sharedInstance
{
static dispatch_once_t once;
static id sharedInstance;
dispatch_once(&once, ^
{
sharedInstance = [self new];
});
return sharedInstance;
}
Run Code Online (Sandbox Code Playgroud)
+ (Class*)sharedInstance
{
static dispatch_once_t once;
static Class *sharedInstance;
dispatch_once(&once, ^
{
sharedInstance = [self new];
});
return sharedInstance;
}
Run Code Online (Sandbox Code Playgroud)
Ser*_*ruk 33
MySingleton.h
@interface MySingleton : NSObject
+(instancetype)sharedInstance;
+(instancetype)alloc __attribute__((unavailable("alloc not available, call sharedInstance instead")));
-(instancetype)init __attribute__((unavailable("init not available, call sharedInstance instead")));
+(instancetype)new __attribute__((unavailable("new not available, call sharedInstance instead")));
-(instancetype)copy __attribute__((unavailable("copy not available, call sharedInstance instead")));
@end
Run Code Online (Sandbox Code Playgroud)
MySingleton.m
@implementation MySingleton
+(instancetype)sharedInstance {
static dispatch_once_t pred;
static id shared = nil;
dispatch_once(&pred, ^{
shared = [[super alloc] initUniqueInstance];
});
return shared;
}
-(instancetype)initUniqueInstance {
return [super init];
}
@end
Run Code Online (Sandbox Code Playgroud)
小智 6
您可以避免分配类覆盖alloc方法.
@implementation MyClass
static BOOL useinside = NO;
static id _sharedObject = nil;
+(id) alloc {
if (!useinside) {
@throw [NSException exceptionWithName:@"Singleton Vialotaion" reason:@"You are violating the singleton class usage. Please call +sharedInstance method" userInfo:nil];
}
else {
return [super alloc];
}
}
+(id)sharedInstance
{
static dispatch_once_t p = 0;
dispatch_once(&p, ^{
useinside = YES;
_sharedObject = [[MyClass alloc] init];
useinside = NO;
});
// returns the same object each time
return _sharedObject;
}
Run Code Online (Sandbox Code Playgroud)
戴夫是对的,这很好.您可能需要查看Apple关于创建单例的文档,以获取有关实现其他一些方法的提示,以确保在类选择不使用sharedFoo方法时只能创建一个方法.
| 归档时间: |
|
| 查看次数: |
92049 次 |
| 最近记录: |