使用哪种同步方法来确保单例仍然是单例?
+(Foo*)sharedInstance
{
@synchronized(self)
{
if (nil == _sharedInstance)
{
_sharedInstance = [[Foo alloc] init];
...
}
}
return _sharedInstance;
}
Run Code Online (Sandbox Code Playgroud)
还是使用互斥?
#import <pthread.h>
static pthread_mutex_t _mutex = PTHREAD_MUTEX_INITIALIZER;
+(Foo*)sharedInstance
{
pthread_mutex_lock(&_mutex);
if (nil == _sharedInstance)
{
_sharedInstance = [[Foo alloc] init];
...
}
pthread_mutex_unlock(&_mutex);
return _sharedInstance;
}
Run Code Online (Sandbox Code Playgroud)
嗯..对此有何评论?
singleton multithreading memory-management objective-c thread-safety
我试图设计一个帮助方法,它将检索UIManagedDocument,然后打开并返回它,以便我可以从我的应用程序中的几个地方访问相同的UIManagedDocument.
由于我对块不太熟悉,因此我遇到了异步性问题.理想情况下,事件的顺序是这样的:
我可以通过某种方式传递原始块吗?
到目前为止,这是我的代码.任何想法都非常感谢,谢谢.
// This is a dictionary where the keys are "Vacations" and the objects are URLs to UIManagedDocuments
static NSMutableDictionary *managedDocumentDictionary = nil;
// This typedef has been defined in .h file:
// typedef void (^completion_block_t)(UIManagedDocument *vacation);
// The idea is that this class method will run the block when its UIManagedObject has opened
@implementation MyVacationsHelper
+ (void)openVacation:(NSString *)vacationName usingBlock:(completion_block_t)completionBlock
{
// Try to retrieve the relevant UIManagedDocument from managedDocumentDictionary
UIManagedDocument *doc …
Run Code Online (Sandbox Code Playgroud)