我在这里搜索了答案,但是这些都没有解决我的问题...
我已经在Truck Managed Object Subclass
中的核心数据中保存了一些数据。这是代码:
for (NSDictionary *dictTruck in self.trucksArray) {
Truck *truck = [NSEntityDescription insertNewObjectForEntityForName:@"Truck" inManagedObjectContext:_managedObjectContext];
Country *country = [NSEntityDescription insertNewObjectForEntityForName:@"Country" inManagedObjectContext:_managedObjectContext];
NSFetchRequest *truckRequest = [[NSFetchRequest alloc]init];
NSEntityDescription *truckDescription = [NSEntityDescription entityForName:@"Truck" inManagedObjectContext:_managedObjectContext];
[truckRequest setEntity:truckDescription];
NSMutableArray *mutableReq = [[_managedObjectContext executeFetchRequest:truckRequest error:nil]mutableCopy];
self.trucksArray = [[NSMutableArray alloc]initWithArray:mutableReq];
[truck setModel:[dictTruck objectForKey:@"model"]];
[truck setYear:[dictTruck objectForKey:@"year"]];
[truck setCountry:country];
[country setCountryName:[dictTruck objectForKey:@"country"]];
[_managedObjectContext save:nil];
}
这工作得很好。现在,问题是我有要通过
AFNetworking
从服务器下载的JSON,格式如下:{
"trucks": [
{
"model": "Scania",
"year": "2014",
"country": "Sweden"
},
{
"model": "DAF",
"year": "2012",
"country": "Ireland"
}
]
}
该JSON每小时更新一次,因此有旧的JSON数据+新的...现在,我的问题是如何检查核心数据中是否存在此对象,例如:Truck.model = @“Scania”,Truck.year = @“2014”,Truck.Country.countryName = @“瑞典”;如果符合所有这些条件,则不应将其保存在CD中...
提前致谢。
更新:在这段代码中是对核心数据中的对象的请求,因为我已经尝试了许多解决方法。
最佳答案
我认为响应json中应该有一个 UNIQUE truck_id
,像这样
{
"trucks": [
{
"id": "00000001"
"model": "Scania",
"year": "2014",
"country": "Sweden"
},
{
"id": "00000002"
"model": "DAF",
"year": "2012",
"country": "Ireland"
}
]
}
将
id
保存为Truck
模型,每次从服务器获得响应时,只需检查核心数据中是否存在具有相同id
的模型即可。对于每个卡车json,请先进行提取请求
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
request.entity = [NSEntityDescription entityForName:@"Truck" inManagedObjectContext:context];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"truckID = %d", truckIDInResponse];
request.predicate = predicate;
NSError *error = nil;
NSArray *objs = [context executeFetchRequest:request error:&error];
if (error) {
[NSException raise:@"no truck find" format:@"%@", [error localizedDescription]];
}
if (objs.count > 0) {
// there is a truck with same id exsist. Use update method
}else {
// there's no truck with same id. Use insert method
}
truckID
是Truck
模型的属性。