0

在决定在 SO 中发布之前,我搜索并查看了大多数核心数据问题。这有点奇怪,我不知道从这里去哪里。

我正在构建一个 iOS 应用程序,我正在使用 RestKit、Core Data 和 Objective Record。在详细介绍之前,请注意我的 Object Context 和 Object Store for Objective Record 和 RKObjectManager 是相同的。所以我不是在相同的上下文之外引用对象。足够的介绍......

Feed_Items 模型是层次结构中的顶层模型。

--Feed_Items

------OutFit 模型(1 对 1 / 可选)

------服装模型(1-t0-1 / 可选)

Clothe 和 Outfit 都具有相同的属性集,我对“comments”属性特别感兴趣

--服装/服装

------其他领域

------NSSet* 评论对象

当我启动应用程序时,我使用 RestKit(json) 和 Object-Mapping 从服务器加载所有最新的提要。在第一次加载时,我只得到 1 个作为装备的提要项目,并且该装备总共有 7 条评论,其中 5 条是最初加载的。到目前为止一切顺利,我得到了 Feed_Item 对象和相应的 Outfit 以及 NSSet 中的 5 条评论。

现在,当用户想要加载所有以前的评论时,我调用另一个 API 并返回 2 条新评论,这些新评论被成功解析为 Comment 对象。

[objectManager getObjectsAtPath:[NSString stringWithFormat:@"api/outfit/comments/%d",[_feed.outfit.outfit_id intValue]]
             parameters:_params
                success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
                    for( Comment* _comment in [mappingResult array]){
                        [_feed.outfit addCommentsObject:_comment];
                        [_comment save];
                    }
                }
                failure:^(RKObjectRequestOperation *operation, NSError *error) {

                }];

没有任何异常或错误,但是我怀疑最后 2 个 Comment 对象的外键没有在 sqlite db 中更新。请看下面的图片

在此处输入图像描述 为了进一步证明我的观点,我在第二次运行时尝试了以下内容

Outfit *_outfit = [[Outfit where:@"outfit_id == 3"] objectAtIndex:0];
NSLog(@"%@", [_outfit.comments allObjects]);

而且只有5个对象

"<Comment: 0xc185ed0> (entity: Comment; id: 0xc185840 <x-coredata://2C61C98F-0B5F-4111-B681-1E43ABFB33D4/Comment/p6> ; data: <fault>)",
"<Comment: 0xc185c00> (entity: Comment; id: 0xc185820 <x-coredata://2C61C98F-0B5F-4111-B681-1E43ABFB33D4/Comment/p1> ; data: <fault>)",
"<Comment: 0xc185f10> (entity: Comment; id: 0xc185850 <x-coredata://2C61C98F-0B5F-4111-B681-1E43ABFB33D4/Comment/p8> ; data: <fault>)",
"<Comment: 0xc185f70> (entity: Comment; id: 0xc185860 <x-coredata://2C61C98F-0B5F-4111-B681-1E43ABFB33D4/Comment/p9> ; data: <fault>)",
"<Comment: 0xc185e90> (entity: Comment; id: 0xc185830 <x-coredata://2C61C98F-0B5F-4111-B681-1E43ABFB33D4/Comment/p4> ; data: <fault>)"

我不知道最后 2 个对象发生了什么以及为什么它没有连接起来。从图像中可以看出,它已成功保存在数据库中,但看起来关系或外键未设置。知道出了什么问题吗?

干杯

4

1 回答 1

0

对于使用 RestKit + Core Data + Objective Record 的用户,请确保修改 NSManagedObject+ActiveRecord.m 中的 saveTheContext 方法,如下所示。

- (BOOL)saveTheContext {
    if (self.managedObjectContext == nil ||
        ![self.managedObjectContext hasChanges]) return YES;

    NSError *error = nil;
    BOOL save = [self.managedObjectContext saveToPersistentStore:&error];
    if (!save || error) {
        NSLog(@"Unresolved error in saving context for entity:\n%@!\nError: %@", self, error);
        return NO;
    }

    return YES;
} 

这里要注意的关键是对 saveToPersistentStore 的调用,它是 NSManagedObjectContext 上的 RKAdditions 类别。如果没有这个 RestKit 初始化对象,将不会在持久存储中保存任何更改。

我花了一天的时间才弄清楚这一点。

于 2013-07-06T08:36:34.757 回答