在将值应用到托管对象之前没有必要写出 JSON 文件(而且,如果你确实写出 JSON 文件,甚至写到缓存目录,你应该在完成后将它们删除)。
以下是如何将来自 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 做同样的事情很简单,而且可能是更好的学习体验。其他 Foundation 网络方法(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' 范围内。如果不是,或者响应为 nil,我们可能已经收到了一个描述原因的 NSError。如果响应在 200 范围内,我们在将其交给NSJSONSerialization 之前确保 NSData 中有一些内容。解析 JSON 对象后,我们确保它响应相关的 NSDictionary 方法,然后使用键值编码将值应用于托管对象。这假定 JSON 键和值直接映射到托管对象的属性 - 如果它们不映射,则您有许多用于重新映射或转换键和值的选项,这些选项甚至超出了本问题的范围。