gpt4 book ai didi

swift - 如何获取保存的对象数量

转载 作者:行者123 更新时间:2023-11-30 11:16:54 27 4
gpt4 key购买 nike

我创建了一个联系人列表,将联系人保存在核心数据中。我可以按姓名访问联系人,但想知道如何获取到目前为止我已保存的联系人数量。

我认为托管对象上下文能够提供硬币,因为这是为每个添加的新联系人创建空间的原因,但事实并非如此,或者可能我使用错误。

这是代码:

import UIKit
import CoreData

class ViewController: UIViewController {

let managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

@IBOutlet weak var name: UITextField!
@IBOutlet weak var address: UITextField!
@IBOutlet weak var phone: UITextField!

@IBOutlet weak var status: UILabel!

@IBAction func saveContact(_ sender: UIButton) {

let entityDescription = NSEntityDescription.entity(forEntityName: "Contacts", in: managedObjectContext)
let contact = Contacts(entity: entityDescription!, insertInto: managedObjectContext)

contact.name = name.text!
contact.address = address.text!
contact.phone = phone.text!
do {
try managedObjectContext.save()
name.text = ""
address.text = ""
phone.text = ""
status.text = "Contact Saved"
} catch let error {
status.text = error.localizedDescription
}
}

@IBAction func findContact(_ sender: UIButton) {
let entityDescription = NSEntityDescription.entity(forEntityName: "Contacts",
in: managedObjectContext)
let request: NSFetchRequest<Contacts> = Contacts.fetchRequest()
request.entity = entityDescription
let pred = NSPredicate(format: "(name = %@)", name.text!)
request.predicate = pred
do {
var results =
try managedObjectContext.fetch(request as! NSFetchRequest<NSFetchRequestResult>)
if results.count > 0 {
let match = results[0] as! NSManagedObject
name.text = match.value(forKey: "name") as? String
address.text = match.value(forKey: "address") as? String
phone.text = match.value(forKey: "phone") as? String
status.text = "Matches found: \(results.count)"
} else {
status.text = "No Match"
}
} catch let error {
status.text = error.localizedDescription
}
}

最佳答案

您可以使用

获取实体的对象数量
do {
let request: NSFetchRequest<Contacts> = Contacts.fetchRequest()
let numberOfContacts = try managedObjectContext.count(for: request)
print(numberOfContacts)
} catch { print(error) }
<小时/>

旁注:您的 findContact 方法非常麻烦。这是改进版

@IBAction func findContact(_ sender: UIButton) {

let request: NSFetchRequest<Contacts> = Contacts.fetchRequest()
request.predicate = NSPredicate(format: "name = %@", name.text!)
do {
let results = try managedObjectContext.fetch(request)
if let match = results.first {
name.text = match.name
address.text = match.address
phone.text = match.phone
status.text = "Matches found: \(results.count)"
} else {
status.text = "No Match"
}
} catch {
status.text = error.localizedDescription

}
}

关于swift - 如何获取保存的对象数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51660136/

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