【发布时间】:2017-01-24 18:45:49
【问题描述】:
(更新:在下面的编辑 4 中,我肯定找到了问题的原因!)
我正在使用 tableView 和 NSFetchedResultsController。这就是我获取数据的方式(我在viewDidLoad() 中称之为):
let fetchRequest: NSFetchRequest<Entry> = Entry.fetchRequest()
let sortSections = NSSortDescriptor(key: #keyPath(Entry.section), ascending: false)
let sortDate = NSSortDescriptor(key: #keyPath(Entry.date), ascending: true)
fetchRequest.sortDescriptors = [sortSections, sortDate]
fetchRequest.fetchBatchSize = 15 // this seems to have no impact
fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managedObject, sectionNameKeyPath: #keyPath(Entry.section), cacheName: "EntriesCache")
不知何故,这非常慢(当我转到包含此table view 的view controller 时,我注意到了这一点)。
在我的设备上,我在我的数据库中尝试了大约 200 个Entryobjects。 view controller 出现需要 1 秒多一点的时间。但我也尝试了大约 10 个对象,它并没有那么快。 (奇怪的是,在模拟器上速度非常快)
我尝试使用Time Profiler 对其进行分析。在这 1 秒内,CPU 处于 100%。这正常吗?
在我注意到这种缓慢的性能之前,我没有这条线
fetchRequest.fetchBatchSize = 15
我添加了它,但没有任何改变。它甚至没有一点点快。我还打印了加载后获取的对象的计数:
print(fetchedResultsController.fetchedObjects?.count)
它表示所有对象都已加载,而不仅仅是其中的 15 个(因为您在表格视图中一次看不到更多)。这是为什么呢?
我不知道您需要什么代码/信息才能帮助我(我不是性能问题方面的专家)。如果您需要更多,请告诉我。
谢谢你们!
编辑:
我如何访问 managedObjectContext:
lazy var managedObject: NSManagedObjectContext = {
let managedObject = self.appDelegate.persistentContainer.viewContext
return managedObject
}()
编辑 2(也许我找到了原因?):
好的,所以我编辑了我的方案,以便它向我显示所有 SQL 查询。首先,它多次加载 15 行(当 15 是 fetchBatchSize 时)。但之后就变得有趣了:
我没有准确计算它,但我很确定它对数据库中的每个对象执行以下查询(/查询)。我尝试了大约 600 个对象,这些 SQL 查询需要很长时间才能运行:
CoreData: sql: SELECT t0.Z_ENT, t0.Z_PK, Z_FOK_ENTRY FROM ZENTRYTEXT t0 WHERE t0.ZENTRY = ?
CoreData: annotation: sql connection fetch time: 0.0001s
CoreData: annotation: total fetch execution time: 0.0002s for 1 rows.
CoreData: annotation: to-many relationship fault "entryTexts" for objectID 0xd000000006480000 <x-coredata://C53DABDD-5D31-4ADE-B6E7-3ED69454B572/Entry/p402> fulfilled from database. Got 1 rows
CoreData: sql: SELECT 0, t0.Z_PK, t0.Z_OPT, t0.ZTEXT, t0.ZENTRY, t0.Z_FOK_ENTRY FROM ZENTRYTEXT t0 WHERE t0.Z_PK = ?
CoreData: annotation: sql connection fetch time: 0.0001s
CoreData: annotation: total fetch execution time: 0.0002s for 1 rows.
CoreData: annotation: fault fulfilled from database for : 0xd000000007940002 <x-coredata://C53DABDD-5D31-4ADE-B6E7-3ED69454B572/EntryText/p485>
我不知道具体是什么,但我认为这是造成延迟的原因。在执行完这些查询之后,视图控制器就会显示出来。
编辑 3:
这是我的table view 数据源方法:
func numberOfSections(in tableView: UITableView) -> Int {
guard let sections = fetchedResultsController.sections else {
return 0
}
return sections.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let sectionInfo = fetchedResultsController.sections?[section] else {
return 0
}
return sectionInfo.numberOfObjects
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "bitCell") as! BitCell
let entry = fetchedResultsController.object(at: indexPath)
cell.configure(entry: entry)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let entry = fetchedResultsController.object(at: indexPath)
extendBitPopup.fadeIn(withEntry: entry, completion: nil)
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView.contentOffset.y >= 400 {
UIView.animate(withDuration: 0.5, animations: {
self.arrowUpButton.alpha = 1.0
self.arrowUpButton.isEnabled = true
self.arrowUpButton.isUserInteractionEnabled = true
})
} else {
UIView.animate(withDuration: 0.5, animations: {
self.arrowUpButton.alpha = 0.0
self.arrowUpButton.isEnabled = false
self.arrowUpButton.isUserInteractionEnabled = false
})
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let entry = fetchedResultsController.object(at: indexPath)
guard !entry.isFault else {
return 0
}
// this estimates the height the cell needs when the text is inserted
return BitCell.suggestedHeight(forEntry: entry)
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if let sectionInfo = fetchedResultsController.sections?[section] {
let dateFormatter = DateFormatter()
// Entry.section has this format: "yyyyMMdd" I chose this to make a section for each day.
dateFormatter.dateFormat = "yyyyMMdd"
let date = dateFormatter.date(from: sectionInfo.name)!
dateFormatter.dateStyle = .full
dateFormatter.timeStyle = .none
return dateFormatter.string(from: date)
}
return ""
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 25
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let view = UIView()
return view
}
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let moment = UITableViewRowAction(style: .normal, title: "Moment") { (action, indexPath) in
let entry = self.fetchedResultsController.object(at: indexPath)
entry.isMoment = !entry.isMoment
self.appDelegate.saveContext()
tableView.setEditing(false, animated: true)
}
moment.backgroundColor = AppTheme.baseGray
let delete = UITableViewRowAction(style: .destructive, title: "Delete") { (action, index) in
let entry = self.fetchedResultsController.object(at: indexPath)
self.managedObject.delete(entry)
self.appDelegate.saveContext()
tableView.setEditing(false, animated: true)
}
delete.backgroundColor = AppTheme.errorColor
return [delete, moment]
}
编辑4(我找到了原因):
问题出在这个函数上:
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let entry = fetchedResultsController.object(at: indexPath)
guard !entry.isFault else {
return 0
}
return BitCell.suggestedHeight(forEntry: entry)
}
我玩过这个,现在我几乎可以肯定这条线是麻烦制造者:
let entry = fetchedResultsController.object(at: indexPath)
如果我在这一行之前返回一个静态 CGFloat,视图控制器几乎会立即加载(我用 700 个对象对其进行了测试)。此外,它只会获取前 50 个项目(即fetchBatchSize),并且只有在向下滚动时才会加载更多项目。
如果我在这行之后返回,它会获取所有数据(根据许多 SQL 查询),它会变得非常慢,并且会出现整个延迟问题。
所以,我认为如果上面的这一行尝试获取 faulted 的对象(也许它会尝试从数据库或其他东西重新获取),则会出现问题
现在的问题是:如何解决这个问题?我需要Entry 对象来估计单元格高度,但如果我知道该对象没有故障(如果这是问题所在),我只想调用此行。我该怎么做?
【问题讨论】:
-
section和date属性是否已编入索引?如果删除排序描述符,性能会提高吗?如果你删除缓存呢? -
你能详细说明你的 managedObjectContext 是如何设置的吗?
-
是的,谢谢,我就是这个意思。但恐怕它无法解决您的问题。
-
OK - 需要查看 tableview 数据源方法才能真正了解它,但作为第一次尝试,请尝试添加
fetchRequest.relationshipKeyPathsForPrefetching = ["entryTexts.text"]。这应该强制所有 EntryTexts 一次加载,而不是每个条目一次提取。 -
如果对象是错误的,请尝试返回非零高度。作为猜测,tableview 正在尝试查看它是否可以在底部显示另一行。每次返回 0 时,它都会认为“好的,可能我可以挤下一行”并请求下一行的高度等。
标签: ios swift performance core-data nsfetchedresultscontroller