gpt4 book ai didi

ios - 检查以确保核心数据中的实体属性在保存时不相同

转载 作者:行者123 更新时间:2023-11-29 01:21:52 25 4
gpt4 key购买 nike

我有一个正在使用核心数据的应用程序。我的应用程序能够添加新实体并填写该实体的“名称”属性。我不确定如何做是确保不存在使用相同“名称”属性创建的 2 个实体。我读过这篇关于独特约束的文章( Constraints in Core Data ),它似乎有点高于我的水平。所以我试图获取页面顶部的代码并实现它。这是我所拥有的:

// check to see if the name is already saved
// check to see if the name is already saved
let fetchRequest = NSFetchRequest(entityName: "Person")

fetchRequest.resultType = .ManagedObjectIDResultType

let predicate = NSPredicate(format: "name = %@ ", name)

let results = coreDataStack.context.executeFetchRequest(fetchRequest)

if (results.name == personName.text) {
//don't use it!
} else {
//create it!
}

我不确定的部分是 NSPredicate,我想查看我对在每个 Person 实体上找到的“name”属性的提取请求。

最佳答案

这是我最终使用的

// 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)")
}

关于ios - 检查以确保核心数据中的实体属性在保存时不相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34499871/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com