【问题标题】:Can not persist the deletion of a record using Core Data无法使用 Core Data 持久删除记录
【发布时间】:2013-06-13 23:31:15
【问题描述】:

我在一个简单的表格视图应用程序中使用 Core Data,它跟踪用户的练习。当一条记录被删除时,删除会在应用程序的启动过程中持续存在。但是,如果我关闭应用程序并重新打开它,记录会重新出现。用户可以从详细视图中删除记录:

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if([title isEqualToString:@"OK"])
{
    //delete record from database...
    NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"Parameters" inManagedObjectContext:context];
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entityDesc];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name like %@", parameters.name];
    [request setPredicate:predicate];

    NSError *error;
    NSArray *matchingData = [context executeFetchRequest:request error:&error];

    for (NSManagedObject *obj in matchingData) {
        [context deleteObject:obj];

    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

else if([title isEqualToString:@"Cancel"])
{

}
}

我不知道为什么删除的记录会重新出现。这发生在模拟器和设备上。我在模拟器上“重置内容和设置”,但仍然没有运气。

非常感谢任何建议。提前致谢。

【问题讨论】:

    标签: ios xcode core-data


    【解决方案1】:

    上下文是一个“便签本”。 “便签本”概念允许您在该“便签本”中进行本地更改,例如修改记录或删除记录,如果您也决定放弃更改。

    您还可以有多个上下文或“便签本”,通常每个线程中有一个上下文,例如一个用于主线程,另一个用于后台线程。

    现在,如果您确定更改正常,则需要通过保存上下文来保留更改。

    NSError *error = nil;
    [context save:&error];
    

    当然,如果您的应用中还有其他“便签本”,则需要同步您保存在核心数据中的那些更改。

    【讨论】:

      【解决方案2】:

      在完成对托管对象模型的更改后,使用 NSManagedObjectContextsave: 方法

      希望这会有所帮助!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-03-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-07
        • 2012-01-24
        • 2019-01-30
        相关资源
        最近更新 更多