L360ContextWatcher 0.1.1

L360ContextWatcher 0.1.1

测试已测试
语言语言 Obj-CObjective C
许可证 MIT
发布最新发布2016年7月

Yusuf Sobh 维护。



L360ContextWatcher 提供了一个基于 block 的 API,用于监听您的核心数据模型中的变化。不再需要 NSFetchedResultsController 的模板代码!您甚至可以在变化传播到持久存储之前进行响应。它是为 Life360 构建的,已在数百万个设备上使用。

安装

L360ContextWatcher 通过 CocoaPods 提供。要安装它,只需将以下行添加到您的 Podfile 中:

pod "L360ContextWatcher"

用法

示例代码可以在 Example/Tests/Tests.m 或 Example/Tests/SwiftExampleTests.swift 中找到。要运行示例代码,首先克隆存储库,然后从 Example 目录运行 pod install

设置上下文监视器

Objective-C

// Specify the context you want to listen to changes on and (optionally) a context to merge the changes onto this only needs to be done once.
[L360ContextWatcher registerForContextChangeNotificationsInContext:self.context callbackContext:self.changesContext andReturnType:L360ContextWatcherReturnTypeManagedObjects];

Swift

L360ContextWatcher.registerForContextChangeNotificationsInContext(self.context, callbackContext: self.changesContext, andReturnType: L360ContextWatcherReturnType.ManagedObjects)

观察变化

Objective-C

// Register the type of changes you want to observe and callback block to execute
[L360ContextWatcher registerObserver:self changeType:L360ContextChangeInsert entityClass:[Dog class] filterPredicate:nil callback:^(NSArray<__kindof NSManagedObjectModel *> * _Nullable objects) {
    Dog *insertedDog = (Dog *)[objects firstObject];
    if([insertedDog.name isEqualToString:@"Lucky"]) {
        NSLog(@"Lucky was inserted!");
    }
}];

Swift

L360ContextWatcher.registerObserver(self, changeType: .Insert, entityClass: Dog.self, filterPredicate: nil)  { (objects:[NSManagedObject]?) in
    if let insertedDog = objects?.first as? Dog where insertedDog.name == "Lucky" {
        print("Lucky was inserted")
    }
}

筛选谓词

如果您只想监听特定变化,请在 registerObserver 中指定一个 NSPredicate,就像 NSFetchedResultsController 一样。

例如

NSPredicate *heavyDogPredicate = [NSPredicate predicateWithFormat:@"weight > 100"];
[L360ContextWatcher registerObserver:self changeType:L360ContextChangeInsert entityClass:[Dog class] filterPredicate:heavyDogPredicate callback:^(NSArray<__kindof NSManagedObjectModel *> * _Nullable objects) {
    // Code to run when a dog was inserted with matching predicate 
}];

待办事项

更细粒度的更新 - 指定要监听更新的键值路径。

功能请求和改进 - 请创建一个问题并讨论。

注意事项

如文档中所述,当您销毁或解构时,不要调用 unregister observer,否则可能会崩溃。当一个观察者被销毁时,上下文监视器将自动删除对其的引用。

响应 will change 更新:为了捕获在发生之前的一次更新,必须调用有更改的上下文中的 contextWillUpdate,然后您可以在完成块中保存上下文并传播更改。请参阅测试以获取示例。

请确保正确选择您想要监听变化的上下文,这通常是将所有更改传递到持久存储之前的上下文。

作者

Yusuf Sobh,[email protected]

许可证

L360ContextWatcher采用MIT许可证。更多信息请参阅LICENSE文件。