I have this model for Core data:
class Posts: NSManagedObject {
@NSManaged var title: String?
@NSManaged var author: String?
@NSManaged var url: String?
@NSManaged var isFavorite: NSNumber?
}
I want to add favorites functionality to my app.
How can I fetch entities that has attribute isFavorite == true? I have managed to fetch all the data so far, but I need the ones that has specific isFavorite value.
Fetching only the objects with favorite = true is quite easy, you just have to set a predicate with it. Something like this should give you some lights:
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 []
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With