自定义获取核心数据(swift)

时间:2016-02-03 04:57:08

标签: ios swift core-data nsfetchedresultscontroller datamodel

我的数据模型

enter image description here

获取功能

func fetchAndSetResults2(){
    let dataController = DataController.sharedController
    let moc = dataController.managedObjectContext
    let request = NSFetchRequest(entityName: "Cart")
    let formatSort = NSSortDescriptor(key: "cartId", ascending: true)
    request.sortDescriptors = [formatSort] //[formatSort, nameSort]
    request.predicate = NSPredicate(format: "cartToUser.userId = %@", serverUserId)


    fetchedResultController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: moc, sectionNameKeyPath: "cartId", cacheName: nil)
    fetchedResultController.delegate = self

    do {
        try fetchedResultController.performFetch()  
    }
    catch {
        fatalError("Error in fetching records")
    }
}

截图 enter image description here

更新:行数

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    if let sections = fetchedResultController.sections {
        return sections.count
    }
    return 0
}


func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if let sections = fetchedResultController.sections {
        let currentSection = sections[section]
        return currentSection.numberOfObjects
    }
    return 0
}

我是核心数据的新手。我已经从购物车实体获取数据了。我的表视图看起来像截图。看看Cart-user(38)-363690,它在1个购物车ID中显示2个单元格,因为它有2张照片。如何只显示一个单元格,即使它有2张或更多照片?

1 个答案:

答案 0 :(得分:0)

从中我可以理解的是,如果购物车上有照片,它应该只显示一行并显示单元格中的照片数量。为此,numberOfRowsInSection方法应仅返回1.无需返回图像数量。并在cellForRowAtIndexPath方法中根据部分中的照片数配置行。

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
     if let sections = fetchedResultController.sections {
        return sections.count
     }
     return 0
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 1
}


func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
     let title: String
     if let sections = fetchedResultController.sections {
        let currentSection = sections[indexPath.section]
        title  = "\(currentSection.numberOfObjects) Photos"
     } 
     else {
        title  = "0 Photos"
     }
     //set the label title for photos

    return cell
}