当数据不再匹配谓词时,不会调用NSFetchedResultsControllerDelegate

时间:2018-06-11 12:45:46

标签: core-data nspredicate nsfetchedresultscontroller nsmanagedobject

我想解决的问题如下:NSFetchedResultsController的谓词将结果限制为特定条件。但是当数据对象新满足或不满足条件时,NSFetchedResultsControllerDelegate不会被调用。

我的NSFetchedResultsController:

private var _fetchedResultsController : NSFetchedResultsController<CardIndex>? = nil
var fetchedResultController : NSFetchedResultsController<CardIndex> {
    get {
        if _fetchedResultsController == nil {
            let fetchRequest: NSFetchRequest<CardIndex> = CardIndex.fetchRequest()
            fetchRequest.sortDescriptors = [NSSortDescriptor.init(key: "index", ascending: true)]
            fetchRequest.predicate = NSPredicate.init(format: "consumer == %@ AND card.definition != nil AND card.stateInt == 0", consumer)

            _fetchedResultsController = NSFetchedResultsController<CardIndex>.init(fetchRequest: fetchRequest, managedObjectContext: CDManager.shared.one.viewContext, sectionNameKeyPath: nil, cacheName: nil)
            do {
                try _fetchedResultsController?.performFetch()
            } catch {
                Log(.Warning, "...")
            }
            _fetchedResultsController?.delegate = self
        }

        return _fetchedResultsController!
    }
}

此处相关的数据结构(仅限伪代码):

class CardIndex {
    @NSManaged public var index: Int16
    @NSManaged public var consumer: String?
    @NSManaged public var card: CardApplication?
}

class CardApplication {
    @NSManaged public var title: String?
    @NSManaged public var indexes: NSSet?
    @NSManaged public var stateInt: NSNumber?
    @NSManaged public var definition: CardDefinition?
}

当NSFetchedResultsController最初提取数据时,它会正确返回设置为CardApplicationdefinition具有值stateInt的所有0。但是当我在运行时将stateInt的值更改为另一个与谓词条件不匹配的值时,不会调用NSFetchedResultsControllerDelegate来反映数据中的更改。我确保在更改stateInt值后保存托管对象的上下文,我还可以看到保存前的上下文hasChangesCardApplication托管对象也显示了属性的更改changedValues()。在保存更改之前从调试器控制台,其中self是CardApplication对象,我更改了stateInt

(lldb) po managedObjectContext!.hasChanges
true

(lldb) po self.isUpdated
true

(lldb) po self.changedValues()
▿ 1 element
  ▿ 0 : 2 elements
    - key : "stateInt"
    - value : 1

为什么代表没有被调用?

1 个答案:

答案 0 :(得分:1)

当您的FRC配置为获取CardIndex对象时,它只会观察对这些对象的更改。因此,它不会响应对相关CardApplication对象的更改。您可以故意“弄脏”CardIndex,这将触发FRC重新评估谓词,或者放弃FRC并使用您自己的观察者来更新您的UI。