如何仅获取 swift 5 中选定行的 CoreData 结果?
How to fetch CoreData result for only selected row in swift 5?
我怎样才能像 SQL SELECT * FROM user where username="something"
中那样获取 CoreData 值
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let db = appDelegate.persistentContainer.viewContext
let request : NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "User")
let predicate = NSPredicate(format: "username='\(usernameLabel.text!)'")
request.predicate = predicate
do{
let result = try db.fetch(request) as! [NSManagedObject]
var get_email : String = ""
for item in result {
if let email = (item as AnyObject).value(forKey: "email") as? String {
get_email.append(email)
}
}
emailTextField.text = get_email
}
catch let error as NSError{
print(error)
}
在上面的代码中,输出类似于 tester1@tester.comtester2@tester.com
它实际上获取了整个电子邮件列。
你的谓词看起来不错(好吧,你最好使用占位符而不是字符串插值)所以最有可能的问题是用户名字段不是唯一的。
我怎样才能像 SQL SELECT * FROM user where username="something"
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let db = appDelegate.persistentContainer.viewContext
let request : NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "User")
let predicate = NSPredicate(format: "username='\(usernameLabel.text!)'")
request.predicate = predicate
do{
let result = try db.fetch(request) as! [NSManagedObject]
var get_email : String = ""
for item in result {
if let email = (item as AnyObject).value(forKey: "email") as? String {
get_email.append(email)
}
}
emailTextField.text = get_email
}
catch let error as NSError{
print(error)
}
在上面的代码中,输出类似于 tester1@tester.comtester2@tester.com
它实际上获取了整个电子邮件列。
你的谓词看起来不错(好吧,你最好使用占位符而不是字符串插值)所以最有可能的问题是用户名字段不是唯一的。