我的数据模型
获取函数
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")
}
}
更新:行数
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/