ces*_*fry 168 singleton objective-c ios automatic-ref-counting
在Xcode 4.2中使用自动引用计数(ARC)时,如何转换(或创建)编译和行为正确的单例类?
Nic*_*rge 378
完全一样,你(应该)已经这样做了:
+ (instancetype)sharedInstance
{
static MyClass *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[MyClass alloc] init];
// Do any other initialisation stuff here
});
return sharedInstance;
}
Run Code Online (Sandbox Code Playgroud)
如果你想根据需要创建其他实例.这个:
+ (MyClass *)sharedInstance
{
static MyClass *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[MyClass alloc] init];
// Do any other initialisation stuff here
});
return sharedInstance;
}
Run Code Online (Sandbox Code Playgroud)
否则,你应该这样做:
+ (id)allocWithZone:(NSZone *)zone
{
static MyClass *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [super allocWithZone:zone];
});
return sharedInstance;
}
Run Code Online (Sandbox Code Playgroud)
如何使用:
MySingletonClass.h
@interface MySingletonClass : NSObject
+(MySingletonClass *)sharedInstance;
@end
Run Code Online (Sandbox Code Playgroud)
MySingletonClass.m
#import "MySingletonClass.h"
#import "SynthesizeSingleton.h"
@implementation MySingletonClass
SYNTHESIZE_SINGLETON_FOR_CLASS(MySingletonClass)
@end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
87725 次 |
| 最近记录: |