我正在core data
使用swift 3.0
。在我的核心数据中,我有一个实体'用户'有三个属性' name' ,age
和'地址'定义为String。
我想在core data entity
中检查用户名是否已存在。我的代码是
func checkUserAlreadyExists(name:String) -> Bool
{
let appDelegate = UIApplication.shared.delegate as? AppDelegate
let managedContext = appDelegate?.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<UserModel>(entityName: "User")
fetchRequest.predicate = NSPredicate(format: "name = %@",name)
//I have also tried this
//fetchRequest.predicate = NSPredicate(format: "name == %@",name)
do {
let arrUsers:[UserModel] = try managedContext!.fetch(fetchRequest)
print(arrUsers.count)
if(arrUsers.count>0)
{
return true
}
else
{
return false
}
} catch let error as NSError {
print("Could not fetch. \(error), \(error.userInfo)")
return false
}
}
我刚刚输入了一个名为 test 的对象,但它没有提取, arrUsers.count 总是返回 0 。< / p>
我在下面的代码中插入数据
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {return}
let managedContext = appDelegate.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "User",in: managedContext)!
let user:UserModel = NSManagedObject(entity: entity,insertInto: managedContext) as! UserModel
user.name = "test"
user.address = "test address"
user.age = "25"
do {
try managedContext.save()
getAllUsersFromCoreData()
} catch let error as NSError
{
print("Could not save. \(error), \(error.userInfo)")
}
我在Questions
上经历了很多stackoverflow
,但没有找到解决方案