Restkit 将对象映射到 NSArray
Posted
技术标签:
【中文标题】Restkit 将对象映射到 NSArray【英文标题】:Restkit mapping objects to NSArray 【发布时间】:2013-12-20 15:38:32 【问题描述】:我有一个由一些字段组成的对象,例如:
@property (nonatomic, copy) NSString* title;
@property (nonatomic, copy) NSString* body;
@property (nonatomic, copy) NSArray* imageUrls;
@property (nonatomic, copy) NSString* postId;
@property (nonatomic) CLLocationCoordinate2D location;
@property (nonatomic) LTUser *user;
@property (nonatomic) LTPlace *place;
@property (nonatomic, copy) NSArray* comments;
所有NSString
和自定义对象(如LTUser
/LTPlace
)都映射得很好。
但是,我怎样才能映射到(imageUrls
的NSArray
- 这是NSString
/ comments
的数组 - 这是自定义对象的数组(LTComment
))?
"images": [
"http://****.com/images/1385929903887.jpg",
"http://****.com/images/131315313131.jpg",
"http://****.com/images/1351351351.jpg"
]
主要对象的映射:
RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[LTUser class]];
[userMapping addAttributeMappingsFromDictionary:@
@"_id":@"userId",
@"username":@"userName",
@"name":@"name"
];
RKObjectMapping *placeMapping = [RKObjectMapping mappingForClass:[LTPlace class]];
[placeMapping addAttributeMappingsFromDictionary:@
@"_id":@"placeId",
@"image":@"name",
@"name":@"image"
];
RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[LTPost class]];
[mapping addAttributeMappingsFromDictionary:@
@"_id" : @"postId",
@"createdAt" : @"createdAt",
@"body" : @"body",
@"title" : @"title"
];
[mapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"user" toKeyPath:@"user" withMapping:userMapping]];
[mapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"place" toKeyPath:@"place" withMapping:placeMapping]];
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:mapping
method:RKRequestMethodGET
pathPattern:kLTAPIGetPostsRequest
keyPath:@"posts"
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[[RKObjectManager sharedManager] addResponseDescriptor:responseDescriptor];
LT评论映射
RKObjectMapping* commentMapping = [RKObjectMapping mappingForClass:[LTComment class]];
[commentMapping addAttributeMappingsFromDictionary:@
@"user_name":@"userName",
@"text":@"text"
];
【问题讨论】:
显示您当前的映射。和源 JSON。你已经有LTComment
的映射了吗?
在“主要对象的映射:”之后添加了描述
添加了 LTComment 映射。
【参考方案1】:
comments
的映射应该与 user
和 place
的映射一样(显然只是使用不同的映射,commentMapping
)。 RestKit 将确定目标是一个集合,源是一个集合并做正确的事情。
对于imageUrls
,JSON 已经是一个字符串数组,所以 RestKit 基本上可以复制它。您需要做的就是添加到“容器”映射(无论是哪个):
@"images" : @"imageUrls"
【讨论】:
以上是关于Restkit 将对象映射到 NSArray的主要内容,如果未能解决你的问题,请参考以下文章