【发布时间】:2013-12-16 15:19:38
【问题描述】:
方法 swizzling 用于以下单例初始化程序,但我不确定 swizzling 的线程安全性。
当一个线程即将调用一个即将被另一个方法调动的方法时会发生什么? 在有线程要调用该方法的情况下,随时进行调配是否安全?请用官方参考回答。谢谢
#import <dispatch/dispatch.h>
#import <objc/runtime.h>
@implementation MySingleton
static MySingleton * __singleton = nil;
+ (MySingleton *) sharedInstance_accessor
{
return ( __singleton );
}
+ (MySingleton *) sharedInstance
{
static dispatch_once_t __once = 0;
dispatch_once( &__once, ^{
__singleton = [[self alloc] init];
Method plainMethod = class_getInstanceMethod( self, @selector(sharedInstance) );
Method accessorMethod = class_getInstanceMethod( self, @selector(sharedInstance_accessor) );
method_exchangeImplementations( plainMethod, accessorMethod );
});
return ( __singleton );
}
@end
【问题讨论】:
-
这段代码有什么意义? dispatch_once 几乎没有开销。事实上,我敢打赌,检查令牌十几个(可能更多)次比进行这种混杂要快。代码也不太复杂。
-
“请用官方参考资料回答”听起来您希望有人为您搜索文档...
-
我发布了一个答案,但我必须说我不明白你想要完成什么,也不明白你为什么需要 swizzling 来做到这一点。对此的解释将有助于澄清您的问题。
-
请不要使用此代码,即使它有效且“安全”;这太糟糕了。坚持包含 SharedInstance 模式。
标签: objective-c multithreading thread-safety swizzling