[英]custom fetch core data (swift)
My Data Model 我的数据模型
Fetch func 获取功能
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")
}
}
Update: number of row 更新:行数
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
}
I'm new in core data. 我是核心数据的新手。 I'm already fetch data from cart entity.
我已经从购物车实体获取数据。 My table view's looks like the screenshot.
我的表格视图类似于屏幕截图。 Look at Cart-user(38)-363690, it shows 2 cell in 1 cart Id because it has 2 photos.
查看Cart-user(38)-363690,它在1个购物车ID中显示2个单元格,因为它有2张照片。 how to only show one cell even if it has 2 or more photos?
如何只显示一个单元格,即使它有2张或更多张照片?
From this what I can Understand is if photos is there for cart it should show only one row and display the count of photos in the cell. 由此我可以理解,如果购物车中有照片,它应该只显示一行,并在单元格中显示照片计数。 For that the
numberOfRowsInSection
method should return only 1. No need to return number of images. 为此,
numberOfRowsInSection
方法应仅返回1。无需返回图像数。 and in cellForRowAtIndexPath
method configure the row based on number of photos in the section. 并在
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.