【发布时间】:2015-06-26 09:53:16
【问题描述】:
如果在 +sharedInstance 方法之前调用单例类的 init 方法会发生什么..?这会产生一个新对象吗?如果不是,那么如何返回相同的实例?在 sharedInstance 中声明静态变量这一事实会对整体结果产生任何影响..?
+ (LibraryAPI*)sharedInstance
{
// 1
static LibraryAPI *_sharedInstance = nil;
// 2
static dispatch_once_t oncePredicate;
// 3
dispatch_once(&oncePredicate, ^{
_sharedInstance = [[LibraryAPI alloc] init];
});
return _sharedInstance;
}
【问题讨论】:
-
看看这个 SO question
-
你的问题我不清楚。如果我调用 [[LibraryAPI alloc] init] 5 次,它将创建并返回 5 个对象。但是如果我调用 [LibraryAPI sharedInstance] 它总是会返回单例对象。
标签: ios objective-c iphone singleton