Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS Swift | Core data fetch by specific value

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.

like image 646
klaudas Avatar asked May 14 '16 09:05

klaudas


1 Answers

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 []
}
like image 79
Flavio Silverio Avatar answered Oct 09 '22 02:10

Flavio Silverio