RestKit Core Data 一对多映射
Posted
技术标签:
【中文标题】RestKit Core Data 一对多映射【英文标题】:RestKit Core Data mapping one to many 【发布时间】:2013-10-30 10:25:19 【问题描述】:我正在使用 RestKit 将以下 JSON 映射到核心数据。
这是我的模型:
这是我的方法:
RKEntityMapping *userMapping = [RKEntityMapping mappingForEntityForName:NSStringFromClass([User class]) inManagedObjectStore:managedObjectStore];
userMapping.identificationAttributes = @[@"id"];
[userMapping addAttributeMappingsFromDictionary:@
@"birthday":@"birthday",
@"email":@"email",
@"facebook_token":@"facebook_token",
@"first_name":@"first_name",
@"gender":@"gender",
@"interested_in":@"interested_in",
@"last_name":@"last_name",
@"password":@"password",
@"m8_status":@"m8_status",
@"status":@"status",
@"languages": @"languages",
@"hometown":@"hometown",
@"location":@"location",
@"avatar_url":@"avatar_url",
@"mood":@"mood"
];
RKEntityMapping *findUserMapping = [RKEntityMapping mappingForEntityForName:NSStringFromClass([FindUser class]) inManagedObjectStore:managedObjectStore];
findUserMapping.identificationAttributes = @[@"id"];
[findUserMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"users" toKeyPath:@"users" withMapping:userMapping]];
[manager addResponseDescriptorsFromArray:@[
[RKResponseDescriptor responseDescriptorWithMapping:findUserMapping
pathPattern:@"/v1/users"
keyPath:nil statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)]
]];
这是从示例 JSON 中获取对象:
"users": [
"avatar_url": null,
"birthday": "04/11/1984",
"email": "antonina.duminskaya@wildermancruickshank.co.uk", "first_name": "Antonina",
"gender": "female",
"hometown": null,
"id": "5264ee384d61632c4b2f0000",
"interested_in": [
"male",
"female" ],
"languages": [], "last_name": "Duminskaya", "location": null, "m8_status": null,
"mood": null,
"status": null
]
这里:
[objectManager getObjectsAtPath:@"/v1/users" parameters:@@"session_id":session.id success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult)
FindUser *findUsers = [[self.fetchedFindUsersResultsController fetchedObjects] lastObject];
NSLog(@"%@", findUsers.users);
failure:^(RKObjectRequestOperation *operation, NSError *error)
];
我在日志中有消息:
Relationship 'users' fault on managed object (0x8e964a0) <FindUser: 0x8e964a0> (entity: FindUser; id: 0x8da0790 <x-coredata://083BB731-FDD7-4A35-A174-724F50862A02/FindUser/p1> ; data:
id = nil;
users = "<relationship fault: 0x8deb260 'users'>";
)
在 mappingResults 中我有关于 json 的所有结果
【问题讨论】:
【参考方案1】:Core Data 最初将关系表示为通过不一次加载所有对象图来节省内存。
https://developer.apple.com/library/ios/documentation/cocoa/conceptual/CoreData/Articles/cdFaultingUniquing.html
此外,不要使用保留字“id”作为托管对象的 Restkit 标识属性。尝试使用 findUserId 和 userId 并相应地更新您的映射。
【讨论】:
***.com/questions/17910766/…我发现了这个类似的问题,有答案,但对我不起作用 我将“id”更改为“userId”和“findUserId”,它成功了!谢谢!! 您也将id
添加到了映射中,是吗?
但是有一个问题,下次在模拟器上运行时,又出现了这个问题。
这是使用 Core Data 设置 Restkit 并映射一对多关系的完整指南。 medium.com/ios-os-x-development/… 。基本上,您需要将您的一对多关系镜像为对象文件中的 NSSet 属性。以上是关于RestKit Core Data 一对多映射的主要内容,如果未能解决你的问题,请参考以下文章