【问题标题】:CoreData - Computed Property in Background ThreadCoreData - 后台线程中的计算属性
【发布时间】:2011-08-29 20:15:44
【问题描述】:

我正在从CoreData 获取大约 2500 颗星以用于构建星图,并且出于显而易见的原因,我希望在后台线程中进行大部分数学计算以计算坐标等。我的问题是,因为我必须将CoreData 对象作为NSManagedObjectIDs 传递回主线程,所以你将如何计算后台线程中的一组笛卡尔坐标并(最好)将这些坐标设置在NSManagedObject 子类?

对于它的价值,这是我用来从 CoreData 获取并传递给主线程的代码的 sn-p:

// Context and Model
NSManagedObjectContext *context = [self.dataProvider newManagedObjectContext];
NSManagedObjectModel *model = [self.dataProvider sharedManagedObjectModel];

// Fetch the stars
NSArray *stars = [SkyObject getSkyObjectsBetweenMinCoords:minCoords 
                                                maxCoords:maxCoords 
                                                   minMag:self.minimumMagnitude 
                                                   maxMag:self.maximumMagnitude 
                                                    model:model 
                                                  context:context];

NSMutableArray *starIDs = [[NSMutableArray alloc] init];

// Add the star's objectID to the set
for (SkyObject *star in stars) {
    [starIDs addObject:star.objectID];
}

// Pass objects across thread boundaries
[self performSelectorOnMainThread:@selector(updateLocalContextWithObjectIDs:) withObject:starIDs waitUntilDone:YES];

// Release retained memory
[starIDs release];
[context release];

【问题讨论】:

    标签: core-data


    【解决方案1】:

    我可以从您的问题和代码中看出这超出了我的想象。但是 GCD 呢?它是我用于通过 tcp/ip 发送的重复保持活动的内容。无论如何希望它有帮助 http://www.fieryrobot.com/blog/2010/06/27/a-simple-job-queue-with-grand-central-dispatch/

    【讨论】:

      【解决方案2】:

      您通常不会“将 CoreData 对象作为 NSManagedObjectIDs 传递回主线程”,而是执行所有操作,使用在后台线程上运行的上下文设置托管对象,然后在完成后,您会将前台上下文与后台上下文合并。

      当然,传递 managedObjectIDs 是可行的,但这是一种缓慢的方法,尤其是当您有数千个对象要处理时。它也不会像合并那样更新整个对象图。

      【讨论】:

      • you would merge the foreground context with the background context - 你能给我举个例子吗?
      • 参见核心数据编程指南:使用通知在其他线程中跟踪更改developer.apple.com/library/ios/documentation/Cocoa/Conceptual/…
      • 同一篇文章说的与你的答案相反。 To “pass” a managed object from one context another across thread boundaries, you either: Pass its object ID (objectID) and use objectWithID: or existingObjectWithID:error: on the receiving managed object context. 等等...
      猜你喜欢
      • 2018-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-10
      • 2018-06-12
      • 1970-01-01
      相关资源
      最近更新 更多