我正在开发应用程序中的核心数据。 我想从核心数据中获取名称属性。
类ViewController: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")
}
}
我怎么能得到它?
谢谢,
答案 0 :(得分:3)
在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()
}
答案 1 :(得分:2)
在Swift 4.1中。我们将使用NSPredicate来指定我们所需的条件。 NSFetchRequest有一个属性谓词将在这里设置我们的谓词如下。
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let fetch = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
let predicate = NSPredicate(format: "username = %@", argumentArray: ["John"]) // Specify your condition here
// Or for integer value
// let predicate = NSPredicate(format: "age > %d", argumentArray: [10])
fetch.predicate = predicate
do {
let result = try context.fetch(fetch)
for data in result as! [NSManagedObject] {
print(data.value(forKey: "username") as! String)
print(data.value(forKey: "password") as! String)
print(data.value(forKey: "age") as! String)
}
} catch {
print("Failed")
}