测试已测试 | ✗ |
Lang语言 | Obj-CObjective C |
许可证 | MIT |
发布最新发布 | 2016 年 8 月 |
由 Michal Zaborowski 维护。
INSPersistentContainer 由 Michał Zaborowski 为 inspace.io 编写。
开源,100% API 兼容性替换 NSPersistentContainer 用于 iOS8+ 和 macOS 10.10+
您想使用 NSPersistentContainer,但需要支持较旧的 iOS 版本?我创建了 INSPersistentContainer,它是 NSPersistentContainer 的直接替换。我在 iOS10b1 中反向工程了 NSPersistentContainer,您可以在 iOS10b1 中找到它。在 Apple 文档 中关于它的信息并不多,但我找到了 Apple 的一篇备注,它解释了这个类:“NSPersistentContainer 实例包括表示一个功能齐全的 Core Data 程序的所有对象,并为常见模式提供了便利方法和属性。”
INSPersistentContainer 还包含了扩展,用于 NSManagedObjectContext 中的新方法,例如:
/* Whether the context automatically merges changes saved to its parent. Setting this property to YES when the context is pinned to a non-current query generation is not supported.
*/
@property (nonatomic) BOOL automaticallyMergesChangesFromParent;
此外,我添加了用于 automaticallyObtainPermanentIDsForInsertedObjects 的方法,这是常用的。
/**
* If the main context is not the parent of the background context, retrieving the object by ID will fail. The temporary ID only exists in the main context and not in the store. The background context therefore has no access to that ID. In that case, you will need to obtain a permanent object ID for the objects in the main context using the API obtainPermanentIDsForObjects(:error:) before you can retrieve them in the background context.
*/
@property (nonatomic) BOOL ins_automaticallyObtainPermanentIDsForInsertedObjects;
最后,我添加了自定义数据堆栈,它使用 automaticallyMergesChangesFromParent 和 automaticallyObtainPermanentIDsForInsertedObjects,对于后台批量更新工作非常好。
- (INSPersistentContainer *)persistentContainer {
// The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it.
@synchronized (self) {
if (_persistentContainer == nil) {
_persistentContainer = [[INSDataStackContainer alloc] initWithName:@"INSPersistentContainer"];
[_persistentContainer loadPersistentStoresWithCompletionHandler:^(INSPersistentStoreDescription *storeDescription, NSError *error) {
if (error != nil) {
NSLog(@"Unresolved error %@, %@", error, error.userInfo);
abort();
}
}];
}
}
return _persistentContainer;
}
lazy var persistentContainer: INSPersistentContainer = {
let stack = INSDataStackContainer(name: "INSPersistentContainer")
stack.loadPersistentStoresWithCompletionHandler({ desc, error in
if error != nil {
print(error)
abort()
}
})
return stack
}()
[self.persistentContainer performBackgroundTask:^(NSManagedObjectContext * context) {
Entity *desc = (Entity *)[NSEntityDescription insertNewObjectForEntityForName:@"Entity" inManagedObjectContext:context];
desc.name = @"test";
[context save:nil];
}];
persistentContainer.performBackgroundTask { context in
let obj = NSEntityDescription.insertNewObjectForEntityForName("Entity", inManagedObjectContext: context) as! Entity
obj.name = "test"
_ = try? context.save()
}
INSPersistentContainer 在 MIT 许可证下可用。有关更多信息,请参阅 LICENSE 文件。