cancelDownload,context deleteObject - CoreData无法解决问题

时间:2014-01-12 11:42:25

标签: ios core-data nsmanagedobjectcontext

我尝试通过执行以下操作取消下载过程:

 //operation -> AFDownloadRequestOperation
  - (void)cancelDownload: (CDVInvokedUrlCommand*) command{
     [[DownloadManager operation] cancel];
     [CoreDataManager deleteFromQueueWithId:[ command.arguments objectAtIndex: 0]];
  }


 + (void) deleteFromQueueWithId: (NSString * ) entryID {
     NSManagedObjectContext *context = [self managedObjectContext];
     NSFetchRequest * request = [[NSFetchRequest alloc] init];
     [request setReturnsObjectsAsFaults:NO];
     request = [NSFetchRequest fetchRequestWithEntityName: @"Download"];
     [request setReturnsObjectsAsFaults:NO];
     [request setPredicate: [NSPredicate predicateWithFormat: @"id=%@", entryID]];
     [request setFetchLimit: 1];

    NSError *err = nil;
    NSArray *array = [context executeFetchRequest:request error:&err];

   if (err) {
       return;
    }

  [self deleteFromQueue:[array objectAtIndex:0]];
}

+ (BOOL) deleteFromQueue: (NSManagedObject *)item {
  NSManagedObjectContext *context = [self managedObjectContext];
 NSError *err = nil;

  [context deleteObject:item];
  if (![context save:&err]) {
  //        NSLog(@"Cannot save: %@!", [err localizedDescription]);
      return NO;
  }
  return YES;
}

+ (NSManagedObjectContext *) managedObjectContext {
  AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  return [delegate managedObjectContext];
}

当我在删除操作后尝试保存时,一切都通过了,我得到以下错误:

CoreData无法解决'0xa687d60的错误

1 个答案:

答案 0 :(得分:0)

我找到了一个解决方案,就像我在删除文件时提到的那样:

  1. 取消操作流程
  2. 从CoreData
  3. 删除文件

    当没有2做1时一切正常(或没有1做2) 我的解决方案是在'setCompletionBlockWithSuccess'块中添加'isCancelled'条件, 这是代码:

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"File downloaded succesffully!");
        [self reportEndDownload:file withStatusCode:[NSNumber numberWithInt:DOWNLAOD_STATUS_COMPLETE]];
    } failure:^(AFHTTPRequestOperation *reqOperation, NSError *error) {
        //This is the condition which solved my problem
           if ( [operation isCancelled] ) {
              [operation deleteTempFileWithError: &error];
              return;
           }
        }
    }];