【问题标题】:Deleting all table records from core data database using relationship使用关系从核心数据数据库中删除所有表记录
【发布时间】:2014-03-12 12:09:59
【问题描述】:

我正在为我的应用程序使用核心数据,我有 4-5 个表,其中一个是 userProfile 表。我已经在应用程序中实现了注销。如果用户退出应用程序,我会删除用户配置文件,如果使用其他用户帐户登录,则会插入新的。我想从数据库中删除用户配置文件删除的所有记录。我为此使用关系,但即使用户配置文件记录已被删除,它也不会从数据库中删除其他记录。 我想提一提的是所有数据都来自服务。我正在对 userprofile 表和其他表之间创建的关系使用级联删除规则。

【问题讨论】:

  • 您能否展示您的模型的图片以及哪些关系设置为级联
  • 除了 userProfile 之外,我还有 3 个表。我对我为其余表定义的所有关系使用级联。说 UserProfile-->文章将具有级联规则,反之亦然。
  • 你的关系是双向的吗?两端是级联的?
  • 我已经相应地更改了我的代码以删除商店并重新创建一个对我来说完美的工作。我为此使用了下面给出的答案。非常感谢您的支持。

标签: objective-c core-data ios7


【解决方案1】:

您有两种不同的方式来实现这一目标。

首先是删除存储并重新创建。例如,这意味着访问文件系统中的存储并删除 sql 文件。例如,您可以在以下讨论中找到如何实现它:Delete/Reset all entries in Core Data?

第二种解决方案是在UserProfile 实体中创建一个级联关系,以链接其他实体。在后者中,您必须建立一个反向关系(无效将是正确的方法)。有关更多信息,请参阅我在Setting up a parent-child relationship in Core Data 的回答。

这么说,根据我的经验,我不鼓励在 Core Data 中保存用户信息(例如密码)。相反,为此采用钥匙串。有些库以简单的方式封装了钥匙串访问(例如SSKeychain)。

【讨论】:

    【解决方案2】:

    我尝试使用级联规则使用关系,但对我不起作用,所以我使用了Delete/Reset all entries in Core Data 方法。为此使用了以下代码。

    NSError * error; 
    NSURL * storeURL = [[AppDelegate.managedObjectContext persistentStoreCoordinator] URLForPersistentStore:[[[AppDelegate.managedObjectContext persistentStoreCoordinator] persistentStores] lastObject]];
    [AppDelegate.managedObjectContext lock];
    [AppDelegate.managedObjectContext reset];//to drop pending changes 
    //delete the store from the current managedObjectContext    
    if ([[AppDelegate.managedObjectContext persistentStoreCoordinator] removePersistentStore: [[[AppDelegate.managedObjectContext persistentStoreCoordinator] persistentStores] lastObject] error:&error])    
    {        
    // remove the file containing the data   
    [[NSFileManager defaultManager] removeItemAtURL:storeURL error:&error];    
    //recreate the store like in the  appDelegate method   
    [[[AppDelegate managedObjectContext] persistentStoreCoordinator] addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options: @{NSMigratePersistentStoresAutomaticallyOption:@YES, NSInferMappingModelAutomaticallyOption:@YES} error:&error];  
    }    
    [AppDelegate.managedObjectContext unlock];   
    //that's it !  
    

    这对我有用。

    【讨论】:

      猜你喜欢
      • 2017-08-12
      • 2013-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多