我知道现在回答为时已晚。仍然只是想在这里发表我的意见。
当我们使用核心数据存储数据并使用 tableview 呈现数据时,使用NSFetchedResultsController
总是有用且节省时间的。
这是像whatsapp这样的简单场景,它将每天对所有消息进行分组并对来自每个组的消息进行排序:
数据模型:
Message<<------->Conversation
Message{
@NSManaged var body: String?
@NSManaged var seen: NSNumber?
@NSManaged var time: NSDate?
@NSManaged var uid: String?
@NSManaged var conversation: Conversation?
var sectionTitle: String? {
//this is **transient** property
//to set it as transient, check mark the box with same name in data model
return time!.getTimeStrWithDayPrecision()
}
}
初始化NSFetchedResultsController
为:
let request = NSFetchRequest(entityName: "Message")
let sortDiscriptor = NSSortDescriptor(key: "time", ascending: true)
request.sortDescriptors = [sortDiscriptor]
let pred = NSPredicate(format: "conversation.contact.uid == %@", _conversation!.contact!.uid!)
request.predicate = pred
let mainThreadMOC = DatabaseInterface.sharedInstance.mainThreadManagedObjectContext()
fetchedResultsController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: mainThreadMOC, sectionNameKeyPath: "sectionTitle", cacheName: nil)
fetchedResultsController.delegate = self
do {
try fetchedResultsController.performFetch()
} catch {
fatalError("Failed to initialize FetchedResultsController: \(error)")
}
表格视图的数据源将是:
//MARK: Table view data source
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let sectionInfo = fetchedResultsController.sections![section]
let n = sectionInfo.numberOfObjects
return n
}
func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 60
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let sectionInfo = fetchedResultsController!.sections! as [NSFetchedResultsSectionInfo]
return sectionInfo[section].name
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let message = fetchedResultsController.objectAtIndexPath(indexPath) as! Message
let cell = tableView.dequeueReusableCellWithIdentifier(IncomingChatBubbleCell.identifier(), forIndexPath: indexPath) as! IncomingChatBubbleCell
configureCell(cell, indexPath: indexPath)
return cell
}
这将给出如下结果:
希望对你有帮助!!!
更新
这是getTimeStrWithDayPrecision()
日期扩展方法的示例实现:
func getTimeStrWithDayPrecision() -> String {
let formatter = NSDateFormatter()
formatter.timeStyle = .NoStyle
formatter.dateStyle = .ShortStyle
formatter.doesRelativeDateFormatting = true
return formatter.stringFromDate(self)
}