gpt4 book ai didi

iphone - 从 coredata swift 获取特定属性

转载 作者:可可西里 更新时间:2023-11-01 00:20:55 24 4
gpt4 key购买 nike

我正在我的应用程序中开发核心数据。我想从核心数据中获取名称属性。

类 View Controller :UIViewController {

@IBOutlet weak var saveDataBtn:UIButton!
@IBOutlet weak var dataTxtField:UITextField!
@IBOutlet weak var dataLbl:UILabel!
var tasks: [Task] = []
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

@IBAction func saveDataBtnPressed(_sender : UIButton){
print("Save Data.")
let task = Task(context: context)
task.name = dataTxtField.text
(UIApplication.shared.delegate as! AppDelegate).saveContext()
getData()
}

func getData(){
do{
tasks = try context.fetch(Task.fetchRequest())

}catch{
print("Fetching Failed")

}

}

I am attaching my xcdatamodel

如何获取?

谢谢,

最佳答案

在 Swift 4 中,您可以直接访问该属性。

do {
let tasks = try context.fetch(request)
for task in tasks {
print(task.name)
}
} catch let error {
print(error.localizedDescription)
}

已更新 - 如何删除和更新实体的实例。

这里有一些组织代码来处理更新和删除的想法。

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

extension Task {
// to get an instance with specific name
class func instance(with name: String) -> Task? {
let request = Task.fetchRequest()

// create an NSPredicate to get the instance you want to make change
let predicate = NSPredicate(format: "name = %@", name)
request.predicate = predicate

do {
let tasks = try context.fetch(request)
return tasks.first
} catch let error {
print(error.localizedDescription)
return nil
}
}

// to update an instance with specific name
func updateName(with name: String) {
self.name = name
(UIApplication.shared.delegate as! AppDelegate).saveContext()
}

// to delete an instance
func delete() {
context.delete(self)
(UIApplication.shared.delegate as! AppDelegate).saveContext()
}
}

func howItWorks() {
guard let task = Task.instance(with: "a task's name") else { return }
task.updateName(with: "the new name")
task.delete()
}

关于iphone - 从 coredata swift 获取特定属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46732962/

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