[英]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.