I have a an entity in core data that represents a workout model. Each entity has a DayID attribute that represents which day the item falls into as shown in the image.
The code to create and save a specific item is shown below in Swift
@IBAction func doneButtonPressed(sender: AnyObject) {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedObjectContextCreation = appDelegate.managedObjectContext
let entityDescription = NSEntityDescription.entityForName("ExerciseItemModel", inManagedObjectContext: managedObjectContextCreation)
//Sunday
let exerciseItemtoAdd = ExerciseItemModel(entity: entityDescription!, insertIntoManagedObjectContext: managedObjectContextCreation)
exerciseItemtoAdd.dayID = dayName //DayName could be Wednesday
exerciseItemtoAdd.exerciseType = "Cardio"
exerciseItemtoAdd.exerciseName = self.exerciseNameTextField.text!
exerciseItemtoAdd.durationOrSets = durationLabelTextArea.text!
exerciseItemtoAdd.distanceOrReps = distanceLabelTextArea.text!
exerciseItemtoAdd.weight = ""
exerciseItemtoAdd.date = currentDate
appDelegate.saveContext() //Save the elements I just created.
let request: NSFetchRequest = NSFetchRequest(entityName: "ExerciseItemModel")
do {
_ = try managedObjectContextCreation.executeFetchRequest(request)
// success ...
} catch let error as NSError {
// failure
print("Fetch failed: \(error.localizedDescription)")
}
self.dismissViewControllerAnimated(true, completion: nil)
}
I can fetch items specific to a day e.g. Wednesday in cellForRowAtIndexPath using the following code:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let exerciseItem = fetchedResultController.objectAtIndexPath(indexPath) as! ExerciseItemModel
//Check if the DayID is the same as a specific WeekDay e.g. Wednesday
if exerciseItem.dayID == self.weekDayModel.dayName {
//All the code here
}
return Cell!
}
The problem I am hence facing is how do I specify the numbeOfRows in section function to only return the number of items related to a specific dayName. eg. I want only the number of items whose DayID is Wednesday. At the moment the function return all the entities including those with other dayID's from Sunday to Saturday and hence distorts the TableView.
Here is my numberOfRowsInSection function:
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//let exerciseItem = fetchedResultController.
//if exerciseItem.dayID == self.weekDayModel.dayName {
//}
numberOfExerciseItems = fetchedResultController.sections![section].numberOfObjects
return fetchedResultController.sections![section].numberOfObjects
}
Any thoughts or help is greatly appreciated. :)
You want to add a predicate to your NSFetchRequest
like so:
let request: NSFetchRequest = NSFetchRequest(entityName: "ExerciseItemModel")
request.predicate = NSPredicate("dayID == %@",self.weekDayModel.dayName)