前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >完整版单例代码

完整版单例代码

作者头像
用户1451823
发布2018-09-13 17:26:19
8351
发布2018-09-13 17:26:19
举报
文章被收录于专栏:DannyHoo的专栏DannyHoo的专栏

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://cloud.tencent.com/developer/article/1338220

#if 0

  • (SingleCase *)sharedSingleCase

{

// 上锁

@synchronized(self){

if (singleCase == nil) {

// 几种单例写法

// singleCase = [SingleCase alloc init];

// singleCase = [SingleCase allocWithZone:<#(struct _NSZone *)#>;

// singleCase = [self alloc init];

// singleCase = [self allocWithZone:NULL init];

            singleCase = [super allocWithZone:NULL init];

        }

    }

return singleCase;

}

#endif

// 有一种单例的写法

  • (SingleCase *)sharedSingleCase

{

static dispatch_once_t oneToken;

dispatch_once(&oneToken, ^{

singleCase = [super allocWithZone:NULL init];

    });

return singleCase;

}

  • (id)copyWithZone:(NSZone *)zone

{

return self;

}

  • (id)mutableCopyWithZone:(NSZone *)zone

{

return self;

}

// 重写allocWithZone    防止别人alloc

  • (instancetype)allocWithZone:(struct _NSZone *)zone

{

return SingleCase sharedSingleCase;

}

//  防止copy   返回的还是同一个对象

  • (id)copyWithZone:(struct _NSZone *)zone

{

return SingleCase sharedSingleCase;

}

  • (id)mutableCopyWithZone:(struct _NSZone *)zone

{

return SingleCase sharedSingleCase;

}

  • (oneway void)release

{

}

  • (instancetype)autorelease

{

return self;

}

  • (instancetype)retain

{

return self;

}

  • (NSUInteger)retainCount

{

// 很大的一个数    release消息并没有什么卵用

return NSUIntegerMax;

}

// 全局静态变量 可以实现对象之间共享 静态存储区

static NSString * phoneNum = nil;

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015年09月08日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档