Swift:在核心数据模型中搜索字符串

Pis*_*san 3 core-data nsfetchrequest ios swift

我遇到了Swift中的以下问题.

我编写了以下函数来检索模型中所有使用name"David"的人.

private func myFetchRequest()
{
    let moc = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext

    let myRequest = NSFetchRequest(entityName: "RegisterOfPersons")

    myRequest.predicate = NSPredicate(format: "name = %@", "David")

    do{
        let results = try moc.executeFetchRequest(myRequest)

        for result in results
        {
             print(result)
        }

    } catch let error{
        print(error)
    }
}
Run Code Online (Sandbox Code Playgroud)

即使我的模型包含两个attribute名为="David"的条目,该行

myRequest.predicate = NSPredicate(format: "name = %@", "David")
Run Code Online (Sandbox Code Playgroud)

找不到这些条目,因为"name"是我模型中的可选属性.我是否必须搜索Optional("David"),意思是什么myRequest.predicate = NSPredicate(format: "name = %@", Optional("David"))?

如何在模型中搜索名为"David"的所有条目?我究竟做错了什么?

谢谢你的帮助!

Nir*_*v D 8

你是这样预测的,string所以将你的比较名称用这样的单引号括起来

myRequest.predicate = NSPredicate(format: "name = '%@'", "David")  
Run Code Online (Sandbox Code Playgroud)

也试试 Contains

myRequest.predicate = NSPredicate(format: "name CONTAINS[cd] %@", "David") 
Run Code Online (Sandbox Code Playgroud)