7

我正在尝试将以下 JSON 的关系映射到 CoreData 支持的模型。

这是 JSON:

{
    "photos": [
        {
            "id": 1,
            "thumb": "http://localhost/test_1_thumb.png",
            "image": "http://localhost/test_1.png",
            "date": "2011-07-02T06:06:16Z",
            "likes": 0,
            "user": {
                "id": 1,
                "username": "User1",
                "avatar": "http://cdn.domain.com/avatar.jpg"
            },
            "comments": [
                {
                    "date": "2011-07-02T06:06:16Z",
                    "text": "This is the only comment",
                    "id": 1,
                    "author": {
                        "username": "User1",
                        "id": 1,
                        "avatar": "http://cdn.domain.com/avatar.jpg"
                    }
                }
            ]
        }
    ]
}

我用 RestKit 的 OM2 类映射的 CoreData 模型。

核心数据实体

照片课。

@interface Photo : NSManagedObject

@property (nonatomic, retain) NSString * thumbnailUrl;
@property (nonatomic, retain) NSString * imageUrl;
@property (nonatomic, retain) NSDate * date;
@property (nonatomic, retain) NSNumber * likes;
@property (nonatomic, retain) NSNumber * photoID;
@property (nonatomic, retain) User *owner;
@property (nonatomic, retain) NSSet *comments;

@end

@interface Photo (CoreDataGeneratedAccessors)

- (void)addCommentsObject:(Comment *)value;
- (void)removeCommentsObject:(Comment *)value;
- (void)addComments:(NSSet *)values;
- (void)removeComments:(NSSet *)values;

@end

@implementation Photo

@dynamic thumbnailUrl;
@dynamic imageUrl;
@dynamic date;
@dynamic likes;
@dynamic photoID;
@dynamic owner;
@dynamic comments;

@end

现在我不完全确定的部分是关系:

// Map relationships between entities.
[commentMapping mapKeyPath:@"author" toRelationship:@"author" withMapping:userMapping];
[photoMapping mapKeyPath:@"user" toRelationship:@"owner" withMapping:userMapping];
[photoMapping mapKeyPath:@"comments" toRelationship:@"comments" withMapping:commentMapping];

有了这个,我可以访问除comments照片属性之外的所有内容,但出现以下错误:Comments = Relationship 'comments' fault on managed object。我感觉这与comments定义为 NSSet 的 Photo 模型有关,或者我在关系映射方面做错了,但我不确定。

4

2 回答 2

7

事实证明,问题与 RestKit 或映射无关,而是我对 CoreData 功能的理解。

我正在访问我的 delgate 中的映射 JSON 对象,如下所示:

- (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObjects:(NSArray*)objects {
    NSLog(@"Loaded photos: %@", objects);

    for (id object in objects) {
        Photo *photo = object;
        // Print other photo attributes...

        NSLog(@"Comments = %@", photo.comments );
    }
}

问题在于尝试直接打印集合对象。CoreData 不会在数据存储上引发故障。简单地替换为如下的快速迭代并访问属性允许我访问评论对象。

for (Photo *photo in objects) {
    for (Comment *comment in photo.comments) NSLog(@"Comment = %@", comment.text);
}
于 2011-08-09T23:54:57.213 回答
2

你需要类似的东西:

[objectManager.mappingProvider setMapping:commentMapping forKeyPath:@"comments"];

还结帐 https://github.com/RestKit/RestKit/wiki/Object-mapping

于 2011-08-09T08:02:18.017 回答