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

发布了34 篇原创文章 · 获赞 20 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/ZhangWangYang/article/details/97657868