gpt4 book ai didi

ios - 与 RestKit 的嵌套对多关系

转载 作者:可可西里 更新时间:2023-11-01 03:29:47 26 4
gpt4 key购买 nike

我正在尝试将以下 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 模型。

CoreData Entities

照片类。

@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 的照片模型有关,或者我在关系映射方面做错了,但我不确定。

最佳答案

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

我在我的委托(delegate)中访问映射的 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);
}

关于ios - 与 RestKit 的嵌套对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6971337/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com