英文:
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)")
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论