我在使用 RestKit 和 CoreData 时遇到了一些困难,尤其是因为 RestKit 0.20 的示例和文档很少。
我有一个(托管)对象Song
,它与Album
. 以下代码可以发布 JSON,但不能以扁平化格式发布,服务器除外。
// Defined elsewhere
Album *theAlbum;
RKObjectManager *objMan = [self objectManager];
// Response Mapping
RKObjectMapping *responseMapping = [RKObjectMapping mappingForClass:[Song class]];
[responseMapping addAttributeMappingsFromDictionary:@{ @"song": @"songID" }];
NSIndexSet *statusCodes = RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful);
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:responseMapping
pathPattern:@"/api/song"
keyPath:nil
statusCodes:statusCodes];
// Request Mapping
RKObjectMapping *requestMapping = [RKObjectMapping requestMapping];
RKEntityMapping *albumRelationshipMapping = [RKEntityMapping mappingForEntityForName:@"Album" inManagedObjectStore:[objMan managedObjectStore]];
[albumRelationshipMapping addAttributeMappingsFromDictionary:@{@"id": @"albumID", }];
[requestMapping addAttributeMappingsFromDictionary:@{ @"title": @"title", @"length": @"length" }];
[requestMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"album"
toKeyPath:@"album"
withMapping:albumRelationshipMapping]];
requestMapping = [requestMapping inverseMapping];
RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:requestMapping objectClass:[Song class] rootKeyPath:nil];
[objMan addRequestDescriptor:requestDescriptor];
[objMan addResponseDescriptor:responseDescriptor];
// Create a new temporary song object
Song *song = [NSEntityDescription insertNewObjectForEntityForName:@"Song"
inManagedObjectContext:[[objMan managedObjectStore] mainQueueManagedObjectContext]];
song.title = @"Some Title";
song.length = 123;
song.album = theAlbum;
// Post operation
objMan.requestSerializationMIMEType = RKMIMETypeJSON;
RKManagedObjectRequestOperation *operation = [objMan appropriateObjectRequestOperationWithObject:song
method:RKRequestMethodPOST
path:@"/api/song"
parameters:nil];
[operation setCompletionBlockWithSuccess:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
// Success
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
// Failure
}];
[objMan enqueueObjectRequestOperation:operation];
此代码将发布这样的 JSON 正文:
{"title":"Some Title","length":"123","album":{"id":"6e32ae476815f365"}}
但是,服务器需要这样的 JSON 正文:
{"title":"Some Title","length":"123","album":"6e32ae476815f365"}
即关系album
应该是一个扁平的外键而不是一个嵌套的对象。但是当我尝试改变albumRelationshipMapping
这样的:
[albumRelationshipMapping setIdentificationAttributes:@[ @"albumID" ]];
[albumRelationshipMapping addAttributeMappingToKeyOfRepresentationFromAttribute:@"albumID"];
它引发异常。( NSInvalidArgumentException', reason: '*** -[NSProxy doesNotRecognizeSelector:allKeys] called!'
)
有人知道我在这里做错了什么吗?或者是否有示例代码可以引导我朝着正确的方向前进?
对不起,如果这个问题已经在其他地方得到了回答。我搜索了所有 stackoverflow 和 google 组,但找不到适合我的案例的特定解决方案(RestKit 0.20,CoreData,与 FK 的关系)。
谢谢,德克