转自 : http://www.devdiv.com/forum.php?mod=viewthread&tid=121163
{
@synchronized(self)
{
if (!g_instance) {
g_instance = [[IPTVMsgCenter alloc] init];
}
}
return g_instance;
}
在单例中都有上面的一个函数,我想问一下为什么这时候这个单例还没有创建就可以用@synchronized(self)呢?
@synchronized()的参数是作为标示,如果我写个MyLock传入也是可以的,这里self也是个标示,你的疑惑是self明明没有实例,传入有什么用?你忽略了个细节,你看看这个是什么方法,静态方法,OBjective-C语言是运行时检测,所以在调用过程中,静态方法的self等于[IPTVMsgCenter Class];所以这样写
@synchronized([IPTVMsgCenter Class]){}也是可以的,这下懂了吧
你自己做个测试,在静态方法中看下if(self == [Class clas])是否成立