Restkit:从核心数据获取到服务器的 POST 对象数组
Posted
技术标签:
【中文标题】Restkit:从核心数据获取到服务器的 POST 对象数组【英文标题】:Restkit: POST array of objects fetched from Core Data to server 【发布时间】:2012-06-18 21:52:28 【问题描述】:我似乎在将一组核心数据对象发布到服务器时遇到了一些问题。 RestKit 使 GET 请求变得非常容易,但在发布时就不那么容易了。
这是服务器想要 JSON 的方式
"myThingList":[
"id":"0",
"code":"8406014415007DC8",
"timestamp":"2012-05-11-12.30.15.505000",
"status":"0",
"userId":"8000000",
]
我在 Core Data 中有一个 THING 类,它最多可以容纳 200 个东西。我需要一次将所有这些发送到服务器。当然,我从 CD 获取后的 NSArray 只是一个 Array of THINGS。
下面是我的代码。我得到 [valueForUndefinedKey:]: 这个类不符合键 theId 的键值编码。'
RKManagedObjectMapping *thingMapping = [ RKManagedObjectMapping mappingForClass:[thingMapping class]
inManagedObjectStore:self.objectManager.objectStore ];
[thingMapping mapKeyPath:@"id" toAttribute:@"theId"];
[thingMapping mapKeyPath:@"code" toAttribute:@"code"];
...... the rest of the fields in Thing
[self.objectManager.mappingProvider setMapping:thingMapping forKeyPath:@"myThingList"];
attendReadMapping.primaryKeyAttribute = @"theId";
[self.objectManager.mappingProvider setSerializationMapping:[thingMapping inverseMapping] forClass:[Things class]];
//now, we create mapping for the MySyncEntity
RKObjectMapping *syncEntityMapping = [RKObjectMapping mappingForClass:[MySyncEntity class]];
[syncEntityMapping mapKeyPath:@"mySyncArray" toRelationship:@"mySyncArray" withMapping:thingMapping];
[[self.objectManager mappingProvider] setSerializationMapping:[syncEntityMapping inverseMapping]
forClass:[MySyncEntity class]];
MySyncEntity *mySyncInstance = [[MySyncEntity alloc] init];
mySyncInstance.mySyncArray = things;
NSString *url = [NSString stringWithFormat:@"things];
if ( [things count] > 0 )
[self.objectManager sendObject:mySyncInstance toResourcePath:url usingBlock:^(RKObjectLoader* postLoader)
postLoader.delegate = aDelegate;
postLoader.method = RKRequestMethodPOST;
postLoader.userData = @"howdy";
postLoader.serializationMIMEType = RKMIMETypeJSON;
[postLoader setUsername:[prefs objectForKey:@"me"]];
[postLoader setPassword:[prefs objectForKey:@"me"]];
postLoader.targetObject = nil; // Map the results back onto a new object instead of self
];
【问题讨论】:
【参考方案1】:发现问题。下面需要改一下
** OLD **
[syncEntityMapping mapKeyPath:@"mySyncArray" toRelationship:@"mySyncArray" withMapping:thingMapping];
** NOW **
[syncEntityMapping mapKeyPath:@"myThingList" toRelationship:@"myThingList" withMapping:thingMapping];
MySyncEntity 类还需要将其 NSArray Prop 更改为同名“myThingList”而不是“mySyncArray”
还有这个
mySyncInstance.mySyncArray = things;
需要
mySyncInstance.myThingList = things;
【讨论】:
以上是关于Restkit:从核心数据获取到服务器的 POST 对象数组的主要内容,如果未能解决你的问题,请参考以下文章
RestKit:如何删除核心数据条目以保持内容与服务器同步?
使用 managedObjectCache 时的 Restkit 映射