RestKit 相当新我在下载公共要点数据时遇到了问题。
我创建了一个RKObjectManager
和两个RKResponseDescriptor
具有相应RKEntityMapping
对象的对象,如下所示。
RKEntityMapping *userEntityMapping = [RKEntityMapping mappingForEntityForName:@"User" inManagedObjectStore:managedObjectStore];
userEntityMapping.identificationAttributes = @[@"userID"];
[userEntityMapping addAttributeMappingsFromDictionary:@{
@"id" : @"userID",
@"avatar_url" : @"avatarURL",
@"gravatar_id" : @"gravatarID",
@"url" : @"jsonURL",
@"login" : @"login"}];
RKResponseDescriptor *userResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:userEntityMapping pathPattern:@"/gists/public" keyPath:@"user" statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[objectManager addResponseDescriptor:userResponseDescriptor];
// Gist Entity
RKEntityMapping *gistEntityMapping = [RKEntityMapping mappingForEntityForName:@"Gist" inManagedObjectStore:managedObjectStore];
gistEntityMapping.identificationAttributes = @[ @"gistID" ];
[gistEntityMapping addRelationshipMappingWithSourceKeyPath:@"user" mapping:userEntityMapping];
[gistEntityMapping addAttributeMappingsFromDictionary:@{
@"id": @"gistID",
@"url": @"jsonURL",
@"description": @"descriptionText",
@"public": @"public",
@"created_at": @"createdAt"}];
RKResponseDescriptor *gistResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:gistEntityMapping pathPattern:@"/gists/public" keyPath:nil statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[objectManager addResponseDescriptor:gistResponseDescriptor];
问题源于有时json中的用户字段为空而我不知道如何处理的问题。事实上我在这里遇到了一个例外
static NSDictionary *RKEntityIdentificationAttributesForEntityMappingWithRepresentation(RKEntityMapping *entityMapping, NSDictionary *representation)
发现这里处理的数组包含空值,导致异常。
- (NSArray *)mapRepresentations:(id)representations atKeyPath:(NSString *)keyPath usingMapping:(RKMapping *)mapping
有没有办法处理这些情况?
编辑:
一个例外是
NSCAssert([representation isKindOfClass:[NSDictionary class]], @"期望一个字典表示");
在RKManagedObjectMappingOperationDataSource
static NSDictionary *RKEntityIdentificationAttributesForEntityMappingWithRepresentation(RKEntityMapping *entityMapping, NSDictionary *representation)
就 JSON 而言,它有时看起来像这样。
{
"url": "https://api.github.com/gists/5661319",
"forks_url": "https://api.github.com/gists/5661319/forks",
"commits_url": "https://api.github.com/gists/5661319/commits",
"id": "5661319",
"git_pull_url": "https://gist.github.com/5661319.git",
"git_push_url": "https://gist.github.com/5661319.git",
"html_url": "https://gist.github.com/5661319",
"files": {
"header.php": {
"filename": "header.php",
"type": "application/httpd-php",
"language": "PHP",
"raw_url": "https://gist.github.com/raw/5661319/12598e6d41015248235058cda806722b30f81dca/header.php",
"size": 173
}
},
"public": true,
"created_at": "2013-05-28T08:29:35Z",
"updated_at": "2013-05-28T08:29:36Z",
"description": "",
"comments": 0,
"user": null,
"comments_url": "https://api.github.com/gists/5661319/comments"
},