【问题标题】:iOS: Core Data class methodiOS:核心数据类方法
【发布时间】:2012-02-23 21:05:02
【问题描述】:

创建一个返回当前 managedObjectContext 实例的 Core Data 类方法是否可行且可行?我想知道这样我就可以转到其他控制器并加载模式视图而无需传递 managedObjectContext。

另外,如果我将 Core Data 与 dispatch_async 一起使用,我知道我需要创建自己的 managedObjectContext 实例,但我可以使用相同的协调器。这会使dispatch_async 和主线程中的信息都可以访问吗?

我基本上是使用dispatch_async 从 API 获取数据并在用户使用应用程序时存储它。

【问题讨论】:

    标签: objective-c multithreading core-data ios5


    【解决方案1】:

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

    【讨论】:

    • 当我需要获取上下文“所以基本上在 viewDidLoad 中”时,只需执行NSManagedObjectContext *context = [[DataManager sharedInstance] managedObjectContext];
    【解决方案2】:

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

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

    - (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]];
    }
    
    }
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-07-29
        • 2011-06-19
        • 1970-01-01
        • 1970-01-01
        • 2018-11-26
        • 1970-01-01
        • 1970-01-01
        • 2014-02-17
        相关资源
        最近更新 更多