Objective-C - 单例

创建一个完整的单例:

#import "SearchDelegate.h"

@interface SearchDelegate() <NSCopying,NSMutableCopying>

@end

static SearchDelegate *sharedSearchDelegate = nil;

@implementation SearchDelegate

+ (instancetype)sharedSearchDelegate
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedSearchDelegate = [[self alloc]init];
    });
    return sharedSearchDelegate;
}

+ (id)allocWithZone:(struct _NSZone *)zone
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedSearchDelegate = [super allocWithZone:zone];
    });
    return sharedSearchDelegate;
}
- (nonnull id)copyWithZone:(nullable NSZone *)zone
{
    return sharedSearchDelegate;
}

- (nonnull id)mutableCopyWithZone:(nullable NSZone *)zone
{
    return sharedSearchDelegate;
}
@end

上一篇:一个 Objective-C 对象的内存结构是怎样的?


下一篇:Objective-C /iphone开发基础:分类(category,又称类别)