ios - 自定义获取核心数据(快速)

标签 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
}

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

最佳答案

据我所知,如果购物车有照片,它应该只显示一行并显示单元格中的照片数。为此,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
}

关于ios - 自定义获取核心数据(快速),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35168805/

相关文章:

ios - 如何在 tableView 中编辑行并保存 coreData 中的更改?

ios - 核心数据 : Fetch Multiple Entities using NSFetchedResultController

ios - 如何在计时器运行时快速将秒数重置为零

iphone - [__NSCFNumber 长度] : unrecognized selector sent to instance 0x6d21350

ios - 应用程序不响应 iOS 7 中的报亭通知(适用于 iOS 6 及更早版本)

cocoa-touch - 如何从分段控件接收输入

ios - 我如何输入检查 CGColor/CGPath?

ios - 核心数据关系映射 : Double Quotes in Value Expression are automatically turned into single quotes

ios - CoreBluetooth 函数不适用于 Singleton

swift - 如何获取指向 Swift 结构的 C 指针的值?