单例

#import <Foundation/Foundation.h>
@class SingleClass;

static SingleClass *instance = nil;

@interface SingleClass : NSObject <NSCopying>
+ (instancetype)shareInstance;
@end

@implementation SingleClass
//类方法,获取单例对象
+ (instancetype)shareInstance{
    if (!instance) {
        instance = [[self alloc] init];
    }
    return instance;
}
//类方法,调用对象的alloc方法时返回已存在的单例
+ (instancetype)allocWithZone:(struct _NSZone *)zone{
    if (!instance) {
        instance = [super allocWithZone:zone];
    }
    return instance;
}
//copy时,返回已存在的单例
- (id)copyWithZone:(NSZone *)zone{
    return instance;
}
//copy时,返回已存在的单例
- (id)copy{
    return instance;
}
@end

posted @ 2015-03-23 09:13  銱ル╬鎯噹  阅读(95)  评论(0编辑  收藏  举报