我正在尝试将以下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模型。
Photo类。
@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模型有关,或者我对关系映射做错了但是我不确定。
答案 0 :(得分: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);
}
答案 1 :(得分:2)
您需要以下内容:
[objectManager.mappingProvider setMapping:commentMapping forKeyPath:@“comments”];