我有许多需要显示来自核心数据存储的数据的视图控制器。
它们中的每一个都从相同的上下文中获取托管对象,但是由于某种原因,当 VC 不止一次进行获取时,托管对象的数量会增加?
managedObjects 不能在同一个上下文中共享并且只能引用指针吗?
当 View Controller 请求相同的数据时,为什么托管对象的数量会增加?
代码:
- (void) updateCacheWithObject:(Object *)object
{
[self.coreDataSaveQueue addOperationWithBlock:^{
NSManagedObjectContext *saveContext = [[NSManagedObjectContext alloc] init];
[saveContext setPersistentStoreCoordinator:[self persistentStoreCoordinator]];
AudioObject *object = [NSEntityDescription
insertNewObjectForEntityForName:@"object"
inManagedObjectContext:saveContext];
[audioObject setValue:object.localPath forKey:@"localPath"];
[audioObject setValue:object.title forKey:@"title"];
[audioObject setValue:object.data forKey:@"data"];
NSError *error;
// does the psc have a store
if ([saveContext.persistentStoreCoordinator.persistentStores count] == 0) {
[saveContext setPersistentStoreCoordinator:[self persistentStoreCoordinator]];
}
if (![saveContext save:&error])
{
NSLog(@"Couldn't save: %@", [error localizedDescription]);
NSLog(@"Error user info dictionary is %@", [error userInfo]);
}
}