使用Web服务同步核心数据
我对CoreData和RESTful Web服务有疑问。 我阅读本教程How To Synchronize Core Data with a Web Service – Part 1关于本地CoreData和远程数据的同步。 我不能因为方法的理解:使用Web服务同步核心数据
- (void)downloadDataForRegisteredObjects:(BOOL)useUpdatedAtDate
的信息始终保存之前的JSON文件
(使用方法:[self writeJSONResponse:responseObject toDiskForClassWithName:className];
)
当所有操作完成则有可能将这些存储在CoreData上。
这是否有一些基本动机?
为什么我们无法直接在CoreData上保存以删除从读/写文件添加的开销? 谢谢
tl; dr保存到磁盘可能是不必要的开销。
我不能评论作者的动机,但我怀疑这是因为该应用程序是作为教程构建的,所以保存到文件是将从Parse.com下载数据的部分和解析JSON的部分分开到CoreData 。
在将值应用于托管对象之前,不需要写出JSON文件(并且,如果您确实将JSON文件写入到缓存目录中,则应在完成时将其删除)。
以下是如何将Web服务响应中的JSON数据应用于核心数据管理对象。
本文使用AFHTTPRequestOperation,所以我们将在这里使用它。请注意,我假设您有一些方法可以获取要应用JSON数据的托管对象。通常这将使用find-or-create模式完成。
AFHTTPRequestOperation *operation = [[SDAFParseAPIClient sharedClient] HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
if (json != nil && [json respondsToSelector:@selector(objectForKey:)]){
// Set the JSON values on the managed object, assuming the managed object properties map directly to the JSON keys
[managedObject setValuesForKeysWithDictionary:json];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Request for class %@ failed with error: %@", className, error);
}];
我假设SDAFParseAPIClient已经解析了JSON。我们检查以确保解析的JSON是NSDictionary
,然后使用Key Value Coding将其应用于托管对象。
使用NSURLConnection
做同样的事情很简单,可能是更好的学习体验。其他基金会联网方式(NSURLSession
等)会的工作几乎相同的方式:
[NSURLConnection sendAsynchronousRequest:request queue:queue completion:(NSURLResponse *response, NSData *data, NSError *error)]
NSIndexSet *acceptableStatusCodes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 99)];
if ([acceptableStatusCodes containsIndex:[(NSHTTPURLResponse *)response statusCode]]){
if ([data length] > 0){
// Parse the JSON
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
if (json != nil && [json respondsToSelector:@selector(objectForKey:)]){
// Set the JSON values on the managed object, assuming the managed object properties map directly to the JSON keys
[managedObject setValuesForKeysWithDictionary:json];
} else {
// handle the error
}
}
} else {
// Handle the error
}
}];
我们发送一个完成块的异步请求。该块通过NSHTTPURLResponse
,NSData
和NSError
。首先,我们检查响应的statusCode
是否在200'OK'范围内。如果不是,或者响应为零,我们可能已经通过了一个描述原因的NSError。如果响应IS在200范围内,我们确保NSData在将其交给NSJSONSerialization
之前有一些内容。一旦解析了JSON对象,我们确保它响应相关的NSDictionary
方法,然后使用键值编码将值应用于管理对象。这假定JSON键和值直接映射到托管对象的属性 - 如果它们不包含,则有许多选项可用于重新映射或变换键和值,这些选项甚至超出此问题的范围。