我对 Core Data 比较陌生,最近玩了一会,无法弄清楚这里出了什么问题。
当我执行以下代码时,一切正常,所有 UI 元素和动画也都很好:
- (void)fetchCoreData {
[self showStatusBarWithStatus:@"Complete"];
dispatch_queue_t backgroundQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(backgroundQueue, ^{
NSManagedObjectContext *backgroundContext = [[NSManagedObjectContext alloc] init];
backgroundContext.persistentStoreCoordinator = [self.appDelegate persistentStoreCoordinator];
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"MyData"];
NSError *error = nil;
NSArray *coreDataObjects = [backgroundContext executeFetchRequest:request error:&error];
if (error)
NSLog(@"Error: %@",error);
self.coreDataArray = [NSMutableArray array];
for (NSManagedObject *object in coreDataObjects) {
NSDictionary *d = [object dictionaryWithValuesForKeys:@[@"uniID",@"uListCount"]];
[coreDataArray addObject:d];
}
[self deleteAllObjects:@"MyData" withContext:backgroundContext]; //Clear Core Data
dispatch_async(dispatch_get_main_queue(), ^{
[self showStatusBarWithStatus:@"Complete"];
});
});
}
- (void) deleteAllObjects: (NSString *) entityDescription withContext:(NSManagedObjectContext*)context {
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:entityDescription inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSError *error;
NSArray *items = [context executeFetchRequest:fetchRequest error:&error];
for (NSManagedObject *managedObject in items) {
[context deleteObject:managedObject];
}
if (![context save:&error]) {
NSLog(@"Error deleting %@ - error:%@",entityDescription,error);
}
}
但是当我删除该行时,[self deleteAllObjects ...];
我的 UI 元素开始混乱。动画没有按应有的方式工作,alpha
属性没有按应有的方式出现(它们0.5f
在应该出现的时候出现1.0f
,或者1.0f
代替0.0f
. 我还删除了删除功能并在 Core Data 的位置添加了一个新对象;问题出似乎除非我对核心数据进行更改(删除或添加条目),否则问题仍然存在。
我确定在如何在后台线程中执行此操作方面我错过了一些东西?