首页 > 解决方案 > iOS Swift Core Data 如何从 NSFetchedResultsController 中搜索 FetchedObjects

问题描述

我有一个EntityAsset. Asset有两个属性id :UUIDdata : 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

我的问题是这个;我需要能够通过我Assetsid搜索而不影响 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所以我确信有一些功能我很幸福地不知道,或者我正在以完全错误的方式接近这个..

实现我想做的事情的最佳方法是什么?

标签: iosswiftcore-datansfetchedresultscontrollernsfetchrequest

解决方案


更有效的方法是

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 }
}

推荐阅读