将后台存储的一组 Core Data 对象传递给主线程的方法是什么?

发布于 2024-12-08 17:08:58 字数 1624 浏览 0 评论 0原文

我的 iOS 项目的一部分会轮询服务器中的对象集,然后将它们转换并保存到 Core Data,然后使用结果更新 UI。服务器任务发生在 NSOperation 类的集合中,我将其称为在后台运行的“服务”。如果 NSManagedObject 及其 ~Context 是线程安全的,我会让服务在主线程上调用委托方法,如下所示:

- (void)service:(NSOperation *)service retrievedObjects:(NSArray *)objects;

当然 你不能像这样传递NSManagedObjects,所以这个委托方法注定要失败。据我所知,有两种解决方案可以从主线程获取对象。但我不喜欢它们,所以我希望伟大的 StackOverflow 社区可以帮助我想出第三个。

  1. 我可以在主线程上执行NSFetchRequest来提取新添加或修改的对象。问题是核心数据存储包含更多这样的对象,因此我必须添加相当多的冗长内容来传达正确的对象集。一种方法是向对象添加一个属性,例如 batchID,然后我可以将其传回委托,以便它知道要获取什么。但是向存储添加数据来修复并发限制感觉是错误的。

  2. 我还可以收集新添加的对象objectID 属性,将它们放入列表中并将该列表发送到委托方法。但不幸的是,我必须在保存上下文之后填充列表,这意味着我必须在后台循环对象两次才能获得正确的列表(第一次是在解析时)服务器响应)。然后我仍然只有一个 objectID 列表,我必须使用 existingObjectWithID:error: 来自主线程上的 NSManagedObjectContext。这看起来太麻烦了。

我缺少什么信息?将一组 NSManagedObject 从后台线程引入主线程而不失去线程限制的第三个解决方案是什么?

Part of my iOS project polls a server for sets of objects, then converts and saves them to Core Data, to then update the UI with the results. The server tasks happens in a collection of NSOperation classes I call 'services' that operate in the background. If NSManagedObject and its ~Context were thread safe, I would have had the services call delegate methods on the main thread like this one:

- (void)service:(NSOperation *)service retrievedObjects:(NSArray *)objects;

Of course you can't pass around NSManagedObjects like this, so this delegate method is doomed. As far as I can see there are two solutions to get to the objects from the main thread. But I like neither of them, so I was hoping the great StackOverflow community could help me come up with a third.

  1. I could perform an NSFetchRequest on the main thread to pull in the newly added or modified objects. The problem is that the Core Data store contains many more of these objects, so I have to add quite some verbosity to communicate the right set of objects. One way would be to add a property to the object like batchID, which I could then pass back to the delegate so it would know what to fetch. But adding data to the store to fix my concurrency limitations feels wrong.

  2. I could also collect the newly added objects' objectID properties, put them in a list and send that list to the delegate method. The unfortunate thing though is that I have to populate the list after I save the context, which means I have to loop over the objects twice in the background before I have the correct list (first time is when parsing the server response). Then I still only have a list of objectIDs, which I have to individually reel in with existingObjectWithID:error: from the NSManagedObjectContext on the main thread. This just seems so cumbersome.

What piece of information am I missing? What's the third solution to bring a set of NSManagedObjects from a background thread to the main thread, without losing thread confinement?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

零時差 2024-12-15 17:08:58

epologee,

虽然您显然有一个满意的解决方案,但我建议您丢失一些有价值的信息,无论项目是通过您的机制更新、删除还是插入的。在我的代码中,我只是将 userInfo 字典迁移到新的 MOC。下面是执行此操作的通用例程:

// Migrate a userInfo dictionary as defined by NSManagedObjectContextDidSaveNotification
// to the receiver context.
- (NSDictionary *) migrateUserInfo: (NSDictionary *) userInfo {

    NSMutableDictionary *ui = [NSMutableDictionary dictionaryWithCapacity: userInfo.count];

    NSSet        *  sourceSet = nil;
    NSMutableSet *migratedSet = nil;

    for (NSString *key in [userInfo allKeys]) {

        sourceSet   = [userInfo valueForKey: key];
        migratedSet = [NSMutableSet setWithCapacity: sourceSet.count];

        for (NSManagedObject *mo in sourceSet) {

            [migratedSet addObject: [self.moc objectWithID: mo.objectID]];
        }
        [ui setValue: migratedSet forKey: key];
    }
    return ui;

} // -migrateUserInfo:

上面的例程假设它是具有 @property NSManagedObjectContext *moc 的类的方法。

我希望您觉得以上内容有用。

安德鲁

epologee,

While you obviously have a solution you are happy with, let me suggest that you lose some valuable information, whether items are updated, deleted or inserted, with your mechanism. In my code, I just migrate the userInfo dictionary to the new MOC. Here is a general purpose routine to do so:

// Migrate a userInfo dictionary as defined by NSManagedObjectContextDidSaveNotification
// to the receiver context.
- (NSDictionary *) migrateUserInfo: (NSDictionary *) userInfo {

    NSMutableDictionary *ui = [NSMutableDictionary dictionaryWithCapacity: userInfo.count];

    NSSet        *  sourceSet = nil;
    NSMutableSet *migratedSet = nil;

    for (NSString *key in [userInfo allKeys]) {

        sourceSet   = [userInfo valueForKey: key];
        migratedSet = [NSMutableSet setWithCapacity: sourceSet.count];

        for (NSManagedObject *mo in sourceSet) {

            [migratedSet addObject: [self.moc objectWithID: mo.objectID]];
        }
        [ui setValue: migratedSet forKey: key];
    }
    return ui;

} // -migrateUserInfo:

The above routine assumes it is a method of a class which has an @property NSManagedObjectContext *moc.

I hope you find the above useful.

Andrew

不回头走下去 2024-12-15 17:08:58

核心数据编程指南中有一部分涉及 与核心数据的并发。简而言之,每个线程应该有自己的托管对象上下文,然后 使用通知来同步上下文。

There's a section of the Core Data Programming Guide that addresses Concurrency with Core Data. In a nutshell, each thread should have its own managed object context and then use notifications to synchronize the contexts.

夜吻♂芭芘 2024-12-15 17:08:58

经过一些实验后,我决定对我提议的方法 2 进行轻微更改。在上下文中执行背景更改时,保留要委托回主线程的对象的分数,例如在 中NSMutableArray *objectsOfInterest。我们最终想要获取此数组中所有对象的 objectID 键,但由于 objectID 值在保存上下文时发生变化,因此我们首先必须执行 <代码>[上下文保存:&错误]。保存后,立即使用下面 NSArray 类别中的 arrayFromObjectsAtKey: 方法生成 objectID 实例列表,如下所示:

NSArray *objectIDs = [objectsOfInterest arrayFromObjectsAtKey:@"objectID"];

您可以安全地传回该数组通过委托进行线程(请确保通过侦听 NSManagedObjectContextDidSaveNotification 使用 mergeChangesFromContextDidSaveNotification 更新主线程上下文)。当您准备好卷入后台操作的对象时,请使用下面类别中的 existingObjectsWithIDs:error: 方法将 objectID 数组重新转换为工作 NSManagedObject< 的列表/代码>s。

任何提高这些方法的简洁性或性能的建议都值得赞赏。

@implementation NSArray (Concurrency)

- (NSArray *)arrayFromObjectsAtKey:(NSString *)key {
   NSMutableArray *objectsAtKey = [NSMutableArray array];
   for (id value in self) {
       [objectsAtKey addObject:[value valueForKey:key]];
   }
   return objectsAtKey;
}

@end

@implementation NSManagedObjectContext (Concurrency)

- (NSArray *)existingObjectsWithIDs:(NSArray *)objectIDs error:(NSError **)error {
    NSMutableArray *entities = [NSMutableArray array];

    @try {
        for (NSManagedObjectID *objectID in objectIDs) {
            // existingObjectWithID might return nil if it can't find the objectID, but if you're not prepared for this,
            // don't use this method but write your own. 
            [entities addObject:[self existingObjectWithID:objectID error:error]];
        }
    }
    @catch (NSException *exception) {
        return nil;
    }

    return entities;
}

@end

After a little experimentation, I decided to go for a slight alteration to my proposed method number 2. While performing background changes on the context, keep a score of the objects you want to delegate back to the main thread, say in an NSMutableArray *objectsOfInterest. We eventually want to get to the objectID keys of all the objects in this array, but because the objectID value changes when you save a context, we first have to perform that [context save:&error]. Right after the save, use the arrayFromObjectsAtKey: method from the NSArray category below to generate a list of objectID instances, like so:

NSArray *objectIDs = [objectsOfInterest arrayFromObjectsAtKey:@"objectID"];

That array you can pass back safely to the main thread via the delegate (do make sure your main thread context is updated with mergeChangesFromContextDidSaveNotification by listening to the NSManagedObjectContextDidSaveNotification). When you're ready to reel in the objects of the background operation, use the existingObjectsWithIDs:error: method from the category below to turn the array of objectID's back into a list of working NSManagedObjects.

Any suggestions to improve the conciseness or performance of these methods is appreciated.

@implementation NSArray (Concurrency)

- (NSArray *)arrayFromObjectsAtKey:(NSString *)key {
   NSMutableArray *objectsAtKey = [NSMutableArray array];
   for (id value in self) {
       [objectsAtKey addObject:[value valueForKey:key]];
   }
   return objectsAtKey;
}

@end

@implementation NSManagedObjectContext (Concurrency)

- (NSArray *)existingObjectsWithIDs:(NSArray *)objectIDs error:(NSError **)error {
    NSMutableArray *entities = [NSMutableArray array];

    @try {
        for (NSManagedObjectID *objectID in objectIDs) {
            // existingObjectWithID might return nil if it can't find the objectID, but if you're not prepared for this,
            // don't use this method but write your own. 
            [entities addObject:[self existingObjectWithID:objectID error:error]];
        }
    }
    @catch (NSException *exception) {
        return nil;
    }

    return entities;
}

@end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文