ios - iOS Swift Core Data 如何从 NSFetchedResultsController 中搜索 FetchedObjects
问题描述
我有一个Entity
叫Asset
. Asset
有两个属性id :UUID
和data : NSData
。我有一个NSFetchedResultsController
名为fetchedAssetsController。
我获取所有Assets
使用:
let request = Asset.fetchRequest() as NSFetchRequest<Asset>
do {
fetchedAssetsController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
fetchedAssetsController.delegate = self
try fetchedAssetsController.performFetch()
} catch let error as NSError {
print("Could not get Assets. Error:\(error), \(error.userInfo)")
}
我有一个 tableView 然后填充fetchedAssetsController.fetchedObjects
我的问题是这个;我还需要能够通过我Assets
的id搜索而不影响 tableView 的 fetchedObjects。目前,要查找IDAsset
,我正在执行以下操作;
func findIndexPathOfAssetByID(_ assetID: UUID) -> IndexPath? {
for asset in fetchedAssetsController.fetchedObjects {
if asset.id == assetID {
return fetchedAssetsController.indexPath(forObject: asset)
}
}
return nil
}
这似乎是一种非常不直观且费力的方法。我想过用一秒钟NSFetchedResultsController
的时间来寻找Asset
我想要的id,但我相信这会覆盖我原来使用的TableView
. 因为我还是新手,CoreData
所以我确信有一些功能我很幸福地不知道,或者我正在以完全错误的方式接近这个..
实现我想做的事情的最佳方法是什么?
解决方案
更有效的方法是
func findAsset(by assetID: UUID) -> Asset? {
return (fetchedAssetsController.fetchedObjects as! [Asset]).first{ $0.id == assetID }
}
或者
func findIndexOfAsset(by assetID: UUID) -> Int? {
return (fetchedAssetsController.fetchedObjects as! [Asset]).index{ $0.id == assetID }
}
推荐阅读
- db2 - 如何在 DB2 Warehouse On Cloud 上进行方案级别的备份?
- android - 使用带有离子和电容器的 https 加载 webview
- sql - 向数据库添加索引会更改查询结果
- javascript - 如何在 Javascript 中向 ul 添加图标的 li 项?
- python - 根据列的值绘制 axvspan
- php - 如何在 drupal8 上修复 RewriteBase
- dart - 从底部应用程序栏颤动更改页面
- java - Is there a way to inherit constructors in Kotlin?
- c# - 在 IIS 上运行 .NET 核心和 .NET Web 应用程序
- unit-testing - 运行“tronbox 测试”时出现“PayloadTooLargeError:请求实体太大”