我正在做一个聊天应用程序,我在其中存储每个聊天的聊天时间,现在我需要首先显示最新的聊天记录,分组在部分中,例如:如果我今天有 10 个聊天,它应该在名为 2016 年 7 月 10 日的部分下,最后发送聊天。为此,我按chatTimestamp对列表进行排序,并且我还有另一个存储相应日期的sectionDate字段。下面是核心数据中显示的数据示例格式。
<MyChat.ChatData: 0x7f8b71cdd190> (entity: ChatData; id: 0xd000000000140002 <x-coredata:….> ; data: {
chatDeviceType = ipad;
chatId = 3557;
chatOwnerName = “John Mathew”;
chatReadStatus = 1;
chatStatus = Received;
chatText = “Hi how are you?“;
chatTimestamp = "2015-09-21 10:41:37 +0000";
chatType = Mine;
imageData = nil;
imageUrl = nil;
sectionDate = "Sep 21, 2015";
users = "0xd000000000080000 <x-coredata:…>”;
})
到目前为止,这是我代码的一部分
var fetchedResultsController: NSFetchedResultsController = NSFetchedResultsController()
override func viewDidLoad() {
super.viewDidLoad()
setupFRC(limit: LIMIT)
......
}
func setupFRC(limit limit:Int) {
messageMaxLimit += limit
let objectsCount = self.stack.mainContext.countForFetchRequest(fetchRequest(self.stack.mainContext), error: nil)
NSFetchedResultsController.deleteCacheWithName("Root")
let request = self.fetchRequest(self.stack.mainContext)
self.fetchedResultsController = NSFetchedResultsController(fetchRequest: request,
managedObjectContext: self.stack.mainContext,
sectionNameKeyPath: "sectionDate",
cacheName: "Root")
self.fetchedResultsController.delegate = self
self.messageMaxLimit = self.messageMaxLimit > objectsCount ? objectsCount : self.messageMaxLimit
if objectsCount > self.messageMaxLimit
{
self.fetchedResultsController.fetchRequest.fetchOffset = objectsCount - self.messageMaxLimit
}
self.fetchData()
}
//To fetch data in FRC
func fetchData() {
do {
try self.fetchedResultsController.performFetch()
chatCollectionView.reloadData()
} catch {
assertionFailure("Failed to fetch: (error)")
}
}
func fetchRequest(context: NSManagedObjectContext) -> FetchRequest<ChatData> {
let e = entity(name: "ChatData", context: context)
let fetch = FetchRequest<ChatData>(entity: e)
fetch.predicate = NSPredicate(format: "(SELF.users == %@)", currentUser!)
//Sort by chatTimeStamp
let sortDescriptor = NSSortDescriptor(key: "chatTimestamp", ascending: true)
fetch.sortDescriptors = [sortDescriptor]
return fetch
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
do {
try self.fetchedResultsController.performFetch()
} catch {
assertionFailure("Failed to fetch: (error)")
}
chatCollectionView.reloadData()
}
现在的问题是聊天似乎有正确的顺序,但部分是按字母顺序排列的。但是,如果我进入聊天并发送它,当它从控制器DidChangeContent重新加载时,它会得到纠正。我不知道为什么它最初没有以正确的顺序加载。我为此使用集合视图。我在这里做错了什么吗?
我通过删除 sectionDate 的 NSManaged 属性并像下面一样添加它并使其在核心数据模型中瞬态并且它起作用来解决此问题。
var sectionDate: String {
get {
self.willAccessValueForKey("sectionDate")
var ddtmp = self.primitiveValueForKey("sectionDate") as! String?
self.didAccessValueForKey("sectionDate")
if (ddtmp == nil)
{
ddtmp = Utilities.stringFromDate(self.chatTimestamp!, dateFormat: "MMM dd, yyyy")
self.setPrimitiveValue(ddtmp, forKey: "sectionDate")
}
return ddtmp!
}
}