从核心数据中挑选特定项目

时间:2016-02-01 03:53:18

标签: ios swift core-data nsfetchedresultscontroller

我在核心数据中有一个代表锻炼模型的实体。每个实体都有一个DayID属性,表示项目落入图像中所示的那一天。

enter image description here

创建和保存特定项目的代码如下所示: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)



    }

我可以抓取特定日期的商品,例如星期三在cellForRowAtIndexPath中使用以下代码:

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!


 }

我所面临的问题是如何在section函数中指定numbeOfRows以仅返回与特定dayName相关的项目数。例如。我只想要DayID为星期三的商品数量。 目前,该函数返回所有实体,包括其他dayID从星期日到星期六的实体,从而扭曲了TableView。

这是我的numberOfRowsInSection函数:

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


    }

非常感谢任何想法或帮助。 :)

1 个答案:

答案 0 :(得分:2)

您希望为NSFetchRequest添加谓词,如下所示:

 let  request:  NSFetchRequest = NSFetchRequest(entityName: "ExerciseItemModel")
 request.predicate = NSPredicate("dayID == %@",self.weekDayModel.dayName)