我有核心数据的这个模型:
class Posts: NSManagedObject {
@NSManaged var title: String?
@NSManaged var author: String?
@NSManaged var url: String?
@NSManaged var isFavorite: NSNumber?
}
我想在我的应用中添加收藏夹功能。
如何获取具有属性isFavorite == true的实体?到目前为止,我已设法获取所有数据,但我需要具有特定isFavorite值的数据。
答案 0 :(得分:12)
仅使用favorite = true获取对象非常简单,您只需使用它设置谓词即可。这样的事情会给你一些启示:
class func fetchFavourites(managedObjectContext: NSManagedObjectContext)->[Posts]{
let fetchRequest = NSFetchRequest(entityName: "Posts")
let predicate = NSPredicate(format: "isFavorite = \(NSNumber(bool:true))")
fetchRequest.predicate = predicate
do {
let results = try managedObjectContext.executeFetchRequest(fetchRequest) as! [Posts]
return results
} catch let error as NSError {
}
return []
}