[英]custom fetch core data (swift)
我的数据模型
获取功能
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
}
我是核心数据的新手。 我已经从购物车实体获取数据。 我的表格视图类似于屏幕截图。 查看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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.