无法删除iphone核心数据中的数据

时间:2012-05-14 12:13:27

标签: iphone ipad core-data

在[managedObjectContext deleteObject:device]之后;仍然在设备对象中显示数据。不要从数据库中删除数据。我可以删除数据

if (managedObjectContext == nil) 
{ 
    managedObjectContext = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext]; 
    NSLog(@"After managedObjectContext: %@",  managedObjectContext);
}

NSError *error;

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

NSEntityDescription *entity = [NSEntityDescription entityForName:@"Reserve" inManagedObjectContext:self.managedObjectContext]; 
[fetchRequest setEntity:entity]; 


//    NSSortDescriptor tells defines how to sort the fetched results
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"number" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
NSLog(@"sort count%d",[sortDescriptors count]);


fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:@"Root"];


NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(number = %d)", [sender tag]];

// [fetchRequest setPredicate:predicate];
[fetchedResultsController.fetchRequest setPredicate:predicate];
self.fetchedObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];      
NSLog(@"Count of array::::%d",[fetchedObjects count]);
NSManagedObject *device = [fetchedObjects lastObject];  
NSLog(@"device::::%@",device);

[managedObjectContext deleteObject:device];

 NSLog(@"device::::%@",[fetchedObjects lastObject]);

提前致谢

1 个答案:

答案 0 :(得分:2)

从上下文中删除对象(device)不会导致它在前一个结果集(fetchedObjects)的末尾自动消失。您获取的数组将包含获取时存在的任何对象。它不会自动更新。

您是否尝试在从上下文中删除对象后再次运行获取请求,然后检查设备是否仍显示在结果集中?此外,如果您确实希望对象保持删除状态,那么save您的上下文也是个好主意。

如果需要,可以向NSFetchedResultsController添加一个委托,只要结果集发生变化,就会回调您的代码。然后,您可以将通知用作提示来重新加载阵列。