我对CoreData和RESTful Web服务有疑问。 我阅读了本教程How To Synchronize Core Data with a Web Service – Part 1关于本地CoreData和远程数据的同步。 我无法理解,因为在方法中:
- (void)downloadDataForRegisteredObjects:(BOOL)useUpdatedAtDate
始终在JSON文件上保存信息
(使用方法:[self writeJSONResponse:responseObject toDiskForClassWithName:className];
)
当所有操作完成后,就可以将它们存储在CoreData上。
这有什么潜在的动机吗?
为什么我们不能直接保存在CoreData上以删除从读/写到文件中添加的开销? 感谢
答案 0 :(得分:0)
tl; dr这个保存到磁盘可能是不必要的开销。
我无法评论作者的动机,但我怀疑这是因为应用程序是作为教程构建的,因此保存到文件是将有关从Parse.com下载数据的部分和有关将JSON解析为CoreData的部分。
答案 1 :(得分:0)
在将值应用于托管对象之前,没有必要编写JSON文件(如果你确实编写了JSON文件,甚至到了caches目录,你应该在完成后删除它们。)
以下是如何将Web服务响应中的JSON数据应用于Core Data托管对象。
本文使用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。如果响应在200范围内,我们确保NSData在将其交给NSJSONSerialization
之前有一些内容。解析完JSON对象后,我们确保它响应相关的NSDictionary
方法,然后使用键值编码将值应用于托管对象。这假定JSON键和值直接映射到托管对象的属性 - 如果它们没有,则有许多选项可用于重新映射或转换键和值,这些选项甚至超出了此问题的范围。