核心数据仅在获取数据时干扰UI

时间:2013-09-11 19:31:59

标签: ios 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.0f1.0f而非0.0f {1}}。我还删除了删除功能并在其位置添加了一个新对象到Core Data;问题就消失了。似乎除非我对Core Data进行更改(删除或添加条目),否则问题仍然存在。

我确定在我应该如何在后台线程中执行此操作时,我会错过哪些内容?

0 个答案:

没有答案