OC创建一个单例

18-08-12 23:36 字数 1052 阅读 2457 已编辑

Tools.h

#import <Foundation/Foundation.h>

@interface Tools : NSObject
+ (instancetype)shareInstance;
@end

Tools.m

#import "Tools.h"

@implementation Tools

static Tools *_instance;

+(instancetype)shareInstance
{
    Tools *instance = [[self alloc] init];
    return instance;
}

+(instancetype)allocWithZone:(struct _NSZone *)zone
{
    NSLog(@"%s", __func__);
    if (_instance == nil) {
        NSLog(@"创建了一个对象");
        _instance = [[super allocWithZone:zone] init];
    }
    return _instance;
}
@end

main.m

#import <Foundation/Foundation.h>
#import "Tools.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Tools *t1 = [[Tools alloc] init];
        Tools *t2 = [Tools new];
        Tools *t3 = [Tools shareInstance];

        NSLog(@"t1 %p", t1);
        NSLog(@"t2 %p", t2);
        NSLog(@"t3 %p", t3);
    }
    return 0;
}

输出

2018-08-12 23:35:40.350941+0800 单利[36072:1037763] +[Tools allocWithZone:]
2018-08-12 23:35:40.351266+0800 单利[36072:1037763] 创建了一个对象
2018-08-12 23:35:40.351309+0800 单利[36072:1037763] +[Tools allocWithZone:]
2018-08-12 23:35:40.351327+0800 单利[36072:1037763] +[Tools allocWithZone:]
2018-08-12 23:35:40.351343+0800 单利[36072:1037763] t1 0x103009a30
2018-08-12 23:35:40.351356+0800 单利[36072:1037763] t2 0x103009a30
2018-08-12 23:35:40.351367+0800 单利[36072:1037763] t3 0x103009a30
0人点赞>
关注 收藏 改进 举报
0 条评论
排序方式 时间 投票
快来抢占一楼吧
请登录后发表评论
站长 @ 十七度
文章
384
粉丝
23
喜欢
195
收藏
31
排名 : 1
访问 : 147.83万
私信