Objective c iOS:核心数据类方法

Objective c iOS:核心数据类方法,objective-c,multithreading,core-data,ios5,Objective C,Multithreading,Core Data,Ios5,创建返回managedObjectContext当前实例的核心数据类方法是否可行?我想知道这样我就可以切换到其他控制器并加载模态视图,而不必传递managedObjectContext 另外,如果我将核心数据与dispatch\u async一起使用,我知道我需要创建自己的managedObjectContext实例,但我可以使用相同的协调器。这会使信息在dispatch\u async和主线程中都可以访问吗 我基本上是使用dispatch\u async从API获取数据,并在用户使用应用程序时

创建返回managedObjectContext当前实例的核心数据类方法是否可行?我想知道这样我就可以切换到其他控制器并加载模态视图,而不必传递managedObjectContext

另外,如果我将核心数据与
dispatch\u async
一起使用,我知道我需要创建自己的managedObjectContext实例,但我可以使用相同的协调器。这会使信息在
dispatch\u async
和主线程中都可以访问吗


我基本上是使用
dispatch\u async
从API获取数据,并在用户使用应用程序时存储数据。

过去,我创建了一个核心数据管理器单例类,简化了操作,但这是iOS5/ARC之前的版本,因此需要进行一些更改。

我在尝试将数据从服务器异步获取到应用程序时遇到了类似的问题。我的方法有点不同,但基本上是这样(这是一个4.3项目,所以没有ARC):

以下方法在我的DataUpdater singleton中。第一个方法在应用程序启动时调用:

- (void) update { //download the updates on a new thread

  [NSThread detachNewThreadSelector:@selector(updateThread) 
                           toTarget:self withObject:nil]; 

}
它使用此选择器初始化线程,该选择器仅负责从API下载内容,然后将其传递回要保存的主线程

- (void) updateThread { //the actual update thread

  //New thread, new auto-release pool 
  //(dunno if you need to do anything fancy for ARC)
  NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

  //... 
  //YOUR CODE TO DOWNLOAD (BUT *NOT* SAVE) DATA FROM THE SERVER
  //DON'T CREATE ANY MANAGED OBJECTS HERE
  //...

  //Pass the data to the main thread to perform 
  //the commit to the Core Data Model
  [self performSelectorOnMainThread:@selector(saveUpdate:) 
                         withObject:data waitUntilDone:NO];

  //kill the thread & the auto-release pool
  [NSThread exit];
  [pool release];
}
现在我们回到主线程,数据被添加到核心数据模型,然后上下文被保存

- (void) saveUpdate:(NSArray *) data {

  //add the objects to your Core Data Model

  //and save context
  NSError * error = nil;
  [[[CoreManager defaultCoreManager] CoreContext] save:&error];
  if (error) {
    [NSException raise:@"Unable to save data update" 
                format:@"Reason: %@", [error localizedDescription]];
  } else {
    [[NSNotificationCenter defaultCenter] postNotification:
      [NSNotification notificationWithName:@"DONE" object:nil]];
}

}

只处理问题的第一部分(你不应该真的问多个问题!)你不必传递托管对象上下文-假设你传递的是托管对象?在这种情况下,上下文可作为托管对象本身的属性使用-
.managedObjectContext

只需执行
NSManagedObjectContext*context=[[DataManager sharedInstance]managedObjectContext]当我需要获取上下文“基本上在viewDidLoad中”时?