如何检查核心数据中是否存在对象 [英] How to check if object exists in core data
问题描述
我在这里搜索了答案,但没有一个解决我的问题...
我已经保存了一些数据在核心数据,在卡车托管对象子类
。这里是代码:
I've searched answer here, but none of these solved my problem...
I've saved some data in core data, in Truck Managed Object Subclass
. Here's the code:
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];
}
。现在,问题是我有JSON,我从服务器通过 AFNetworking
以这样的格式下载:
And this works pretty fine. Now, problem is that I have JSON that I'm downloading from server via AFNetworking
in format like this:
{
"trucks": [
{
"model": "Scania",
"year": "2014",
"country": "Sweden"
},
{
"model": "DAF",
"year": "2012",
"country": "Ireland"
}
]
}
这个JSON每小时更新,所以有旧的JSON数据+新...现在,我的问题是如何检查这个对象是否存在于Core Data中,例如:Truck.model = @Scania,Truck.year = @2014,Truck.Country.countryName = @瑞典;如果它匹配所有这些条件,它不应该保存在CD ...
提前感谢。
更新:
在此代码中是核心数据中对象的请求,因为我已经尝试过很多方法来解决这个问题。
推荐答案
在我看来,在应用程序中应该有 UNIQUE truck_id
响应json,像这样
In my opinion there should be a UNIQUE truck_id
in the response json, like this
{
"trucks": [
{
"id": "00000001"
"model": "Scania",
"year": "2014",
"country": "Sweden"
},
{
"id": "00000002"
"model": "DAF",
"year": "2012",
"country": "Ireland"
}
]
}
保存 id 到
到
模型,并且每次从服务器获取响应时,只需检查是否存在具有相同
id
。
Save the id
to Truck
model and every time you get response from server, just check if there is a model with same id
in core data.
对于每个卡车json,首先提出获取请求
For every truck json, make a fetch request first
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
是卡车
模型的属性。
这篇关于如何检查核心数据中是否存在对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!