
1 chisj 2014-04-22 17:48:18 +08:00 我们的单例模式是这么写的,是我最喜欢的写法。给LZ一个参考: static id shareInstance = nil; +(void)initialize { if (self == [EUHttpCache class]) { shareInstance = [[self alloc] init]; } } +(EUHttpCache *)shareInstance { return shareInstance; } |
2 fly2never 2014-04-22 17:56:58 +08:00 用 dispatch_once吧,标准写法 |
3 DropperY 2014-04-22 18:00:11 +08:00 是因为retaincount 写死了 NSUIntegerMax 的原因吧,预期的retaincount应该比原来大1 |
4 alexrezit 2014-04-22 18:00:59 +08:00 via iPhone 是什鬼法... |
5 chchwy 2014-04-22 19:04:47 +08:00 主的法已了。 |
6 ultragtx 2014-04-22 19:28:53 +08:00 via iPad 不能吐槽更多 这都是在哪学的奇葩写法 |
8 adow OP 这样的写法我是从一本obj-c设计模式书上看来的,今天我google了一圈,现在的确都是用 dispatch_once 的写法了,我也改成了这样。不过这个问题在Xcode5.2下依旧。我想应该不是初始化时的问题吧。 |
9 ylovesy 2014-04-22 20:28:39 +08:00 上面的单例不好,应该这样: +(instancetype)sharedInstance { static dispatch_once_t once; static MyObject *sharedInstance = nil; dispatch_once(&once,^{ sharedInstance = [[MyObject alloc] init]; }); return sharedInstance; } |
10 ultragtx 2014-04-22 20:39:08 +08:00 这不只是单例的问题 你这里面除了sharedSingleton以外的所有method都不需要 |
11 jesse0628 2014-04-22 20:48:18 +08:00 @ultragtx 他想达到的目的是,把单例当做正常非单例使用,但不管你alloc还是retain、release,永远只存在一份真正的内存对象。 |
12 satanwoo 2014-04-22 20:54:21 +08:00 楼上正解。而且这样的写法还要考虑到单例中的继承问题。。 |
13 ultragtx 2014-04-22 21:27:26 +08:00 |
14 hengxin196 2014-04-22 23:13:24 +08:00 `#import "__class__.h" @implementation __class__ + (__class__ *)__accessor__ { static dispatch_once_t once; static __class__ *__singleton__; dispatch_once(&once, ^ { __singleton__ = [[__class__ alloc] init]; }); return __singleton__; } @cursor @end` |
15 wangccddaa 2014-04-23 15:38:49 +08:00 + (id)sharedList { static id _sharedInstance = nil; static dispatch_once_t once; dispatch_once(&once, ^{ _sharedInstance = [[self alloc] init]; }); return _sharedInstance; } 上一份我们的代码 把类名改成 self 是不是就是万能单例了,哈哈~ |
16 krafttuc 2014-04-23 16:45:10 +08:00 |
17 msching 2014-04-24 09:47:22 +08:00 lz这个写法多线程环境下会生成多个实例。。 |