相关疑难解决方法(0)

线程安全实例化单例

使用哪种同步方法来确保单例仍然是单例?

+(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

33
推荐指数
3
解决办法
2万
查看次数

如何使用块为整个应用程序共享的每个磁盘文件创建一个全局UIManagedDocument实例?

我试图设计一个帮助方法,它将检索UIManagedDocument,然后打开并返回它,以便我可以从我的应用程序中的几个地方访问相同的UIManagedDocument.

由于我对块不太熟悉,因此我遇到了异步性问题.理想情况下,事件的顺序是这样的:

  1. 类X调用helper方法来检索UIManagedDocument,并包含一个在返回打开的文档时运行的代码块.
  2. 类方法检索UIManagedDocument并根据需要调用openWithCompletionHandler或saveToURL,并包含在返回打开的文档时运行的代码块.
  3. openwithCompletionHandler或saveToURL完成他们的任务,并返回成功= YES并在其块中运行代码
  4. 类方法完成其任务并返回一个打开的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)

iphone block objective-c cs193p ios

11
推荐指数
1
解决办法
6344
查看次数