核心数据:如何检索具有特定属性值的实体?

huangapple go评论72阅读模式
英文:

Core Data: How to Retrieve Entities with a Specific Attribute Value?

问题

在我的iOS应用中,我正在使用Core Data来获取具有特定属性值的实体。假设我有一个名为"Person"的对象,具有属性"name"(String)和"age"(Integer)。如何在Swift中使用Core Data来获取所有"age"属性等于25的"Person"实体?

任何帮助或代码片段将不胜感激。非常感谢!

英文:

In my iOS app, I'm using Core Data to get entities with a specified property value. Assume I have a "Person" object with attributes "name" (String) and "age" (Integer). How can I use Core Data in Swift to get all "Person" entities with the "age" property equal to 25?

Any assistance or code snippets would be highly appreciated. Thank you very much!

答案1

得分: 2

let fetchRequest = NSFetchRequest(entityName: "Person")
// 使用 NSPredicate 如下
fetchRequest.predicate = NSPredicate(format: "age == %@", "25")
do {
    let results = try context.fetch(fetchRequest)
    for result in results as! [NSManagedObject] {
        print(result.valueForKey("name") as! String)
    }
} catch let error as NSError {
    print("无法获取数据 \(error), \(error.userInfo)")
}
英文:
let fetchRequest = NSFetchRequest(entityName: "Person")
// Use NSPredicate like bellow
fetchRequest.predicate = NSPredicate(format: "age == %@", "25")
do {
    let results = try context.fetch(fetchRequest)
    for result in results as! [NSManagedObject] {
        print(result.valueForKey("name") as! String)
    }
} catch let error as NSError {
    print("Could not fetch \(error), \(error.userInfo)")
}

huangapple
  • 本文由 发表于 2023年5月25日 16:39:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76330357.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定