删除核心数据内容时的奇怪行为

时间:2012-10-17 09:47:33

标签: ios iphone core-data

我使用以下代码删除coredata数据库内容...我正确地收到通知..但似乎数据没有被删除...我无法弄清楚...

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
       NSEntityDescription *entity = [NSEntityDescription entityForName:entityDescription inManagedObjectContext:self.managedObjectContext];
       [fetchRequest setEntity:entity];
       NSError *errors;
       NSArray *items = [self.managedObjectContext executeFetchRequest:fetchRequest error:&errors];
       NSLog(@"FinalArray:%@",[finalArray objectAtIndex:currentImageIndex]);
       NSManagedObject *managedObject=[finalArray objectAtIndex:currentImageIndex];
       NSLog(@"NSManagedObject:%@",managedObject);
       for (int i=0;i<[items count];i++)
       {
           if ([managedObject isEqual:[items objectAtIndex:i]])
           {
               [self.managedObjectContext deleteObject:managedObject];
               NSLog(@"gone");
           }
       }
       NSNotificationCenter *nc=[NSNotificationCenter defaultCenter];
       [nc addObserver:self selector:@selector(deleteCheck:) name:NSManagedObjectContextObjectsDidChangeNotification object:self.managedObjectContext];
       NSLog(@"dffsdf%@",[errors description]);
       if (self.managedObjectContext==nil)
       {
           NSLog(@"deleted");
       }

通知功能调用

  - (void)deleteCheck:(NSNotification *)notification 
{
    NSLog(@"CoreData got Deleted");
    NSDictionary *userInfoDictionary = [notification userInfo];
    NSSet *deletedObjects = [userInfoDictionary objectForKey:NSDeletedObjectsKey];
    NSLog(@"DeletedObjects%@",deletedObjects);
}

由于每次点击删除按钮时都会调用NSManagedObjectContextObjectsDidChangeNotification通知...但是在DB中没有效果...建议请

2 个答案:

答案 0 :(得分:0)

你可以使用我使用的这个简单的删除方法,它的工作完美:

-(void)deleteRecords{
NSFetchRequest * deleteRequest = [[[NSFetchRequest alloc] init] autorelease];
[deleteRequest setEntity:[NSEntityDescription entityForName:@"yourTabelName" inManagedObjectContext:context]];
[deleteRequest setIncludesPropertyValues:NO]; //only fetch the managedObjectID

NSError * error = nil;
NSArray * cars = [context executeFetchRequest:deleteRequest error:&error];

if ([cars count] !=0) {      

    //error handling goes here

    for (NSManagedObject * car in cars) {

        [context deleteObject:car];
    }
    NSError *saveError = nil;
    [context save:&saveError];
    //   [tableView reloadData];


}
else {
   NSLog(@"No Data To delete");

} }

答案 1 :(得分:0)

你需要在最后保存。

NSError *error = nil;
[self.managedObjectContext save:&error];