Tidane,
当你需要检查对象是否已经存在与否,你需要设置为获取请求,并使用特定的断言。在你的情况下,你可以简单地获取Ville
,并看看你是否已经有idV
。我想idV
就像是您的Ville
的标识符。检查nom
可能是相同的,但在世界的两个不同地方可以有两个同名的cities
。
@alpz解决方案没问题。另外你还可以设置fecth限制为1:
[request setFetchLimit:1];
否则,你可以简单地做
NSUInteger count = [context countForFetchRequest:request error:&error];
if(count == 0) {
// add the new city here
}
代替
NSArray *results = [context executeFetchRequest:request error:nil];
@Phillip米尔斯是说,你可以使用NSManagedObject
子类而不是使用键值编码访问。我认为使用类的属性而不是纯字符串键更容易。
所以,一旦你已经创建了一个Ville
子类(organising-core-data-for-ios),你可以只为它创建一个类,叫做Ville+Extension
,并创建一个类似如下的方法:
+ (Ville *)villeWithUniqueName:(NSString *)name withManagedObjectContext:(NSManagedObjectContext*)context
{
NSFetchRequest * request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"Ville" inManagedObjectContext:context]];
[request setPredicate:[NSPredicate predicateWithFormat:@"nom = %@", name];
[request setFetchLimit:1];
NSArray *results = [context executeFetchRequest:request error:nil];
Ville* theVille = nil;
if ([results count] == 0)
{
theVille = // create the new here
}
else
{
theVille = (Ville*)[results objectAtIndex:0];
}
[request release]; // if you don't use ARC
return theVille;
}
然后,使用该类别(在进口后)如:
Ville* theVille = [Ville villeWithUniqueName:@"yourName" withManagedObjectContext:yourContext];
希望有所帮助。
非常感谢你...我终于明白了:) – Tidane
@Tidane不客气。干杯。 –