我有一个使用Core Data的应用。我有一个应用程序能够添加一个新的实体并填写"名称"该实体的属性。我不确定该怎么做是确保没有2个实体使用相同的"名称"属性。我已经阅读了这篇关于独特约束的文章(Constraints in Core Data),它似乎比我高。所以我试图将代码放在页面顶部并实现它。这就是我所拥有的:
public void Remove(
params IConvention[] conventions)
我不确定的部分是NSPredicate,我想查看我的取名请求" name"在每个Person Entity上找到的属性。
答案 0 :(得分:1)
以下是我最终使用
的内容// check to see if the name is already saved
let fetchRequest = NSFetchRequest(entityName: "Person")
fetchRequest.resultType = .CountResultType
// check the name attribute against the person name input
let predicate = NSPredicate(format: "name = %@ ", personName.text!)
fetchRequest.predicate = predicate;
do{
let results = try coreDataStack.context.executeFetchRequest(fetchRequest) as! [NSNumber]
let count = results.first!.integerValue
if (count == 0) {
//use it!
print("You can use that name")
}else{
// don't use it!
print("You already have that name in use")
}
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}