pra*_*250 7 core-data objective-c
我是Core Data编程的新手.我有一个问题,我希望得到一些澄清.
假设我有一个NSManagedObject被调用Company,具有以下属性:
在此对象中,companyName属性已编制索引.
所以,我的问题是,我怎样才能确保只有相同的companyName,companyEmail,companyPhoneNo,companyUserName和companyPassword的条目?
我是否需要发出请求以检查是否有任何具有相同属性值的记录,或者是否只是对象ID足够的简单检查?
谢谢.
Kju*_*uly 13
这里有一个例子可能有帮助:
NSError * error;
NSFetchRequest * fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:[NSEntityDescription entityForName:NSStringFromClass([self class])
inManagedObjectContext:managedObjectContext]];
[fetchRequest setFetchLimit:1];
// check whether the entity exists or not
// set predicate as you want, here just use |companyName| as an example
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"companyName == %@", companyName]];
// if get a entity, that means exists, so fetch it.
if ([managedObjectContext countForFetchRequest:fetchRequest error:&error])
entity = [[managedObjectContext executeFetchRequest:fetchRequest error:&error] lastObject];
// if not exists, just insert a new entity
else entity = [NSEntityDescription insertNewObjectForEntityForName:NSStringFromClass([self class])
inManagedObjectContext:managedObjectContext];
[fetchRequest release];
// No matter it is new or not, just update data for |entity|
entity.companyName = companyName;
// ...
// save
if (! [managedObjectContext save:&error])
NSLog(@"Couldn't save data to %@", NSStringFromClass([self class]));
Run Code Online (Sandbox Code Playgroud)
提示:countForFetchRequest:error:实际上不会获取实体,它只返回与predicate之前设置的实体匹配的多个实体.
| 归档时间: |
|
| 查看次数: |
5131 次 |
| 最近记录: |