菜鸟教程小白 发表于 2022-12-13 02:51:53

ios - 重置 Core Data 模型中所有保存的数据


                                            <p><p>我有一个方法允许用户导出我的 <code>Core Data 模型</code> 中所有数据的 .csv 文件。在执行 <code>fetchRequest</code> 后,我正在使用美妙的 <code>CHCSV Parser</code> 来获取存储的结果。创建 .csv 文件后,它会附加到电子邮件中并从设备中导出。这一切都很好,当我删除数据时就会出现问题。</p>

<p>我正在使用一种比较流行的技术来删除我的数据(我所说的流行是指在我研究过的许多 Stack Overflow 答案中都推荐了这种技术)。我只是简单地获取所有对象并一个一个地删除它们。</p>

<pre><code>// Create fetchRequest
NGLSAppDelegate *appDelegate = (NGLSAppDelegate *)[delegate];
NSManagedObjectContext *context = ;
NSFetchRequest *fetchRequest = [init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@&#34;NGLS&#34;
                                                      inManagedObjectContext:context];
;
NSError *error;
NSArray *fetchedObjects = ;

// Delete objects
for (Model *results in fetchedObjects) {
    ;
    NSLog(@&#34;NGLS objects deleted&#34;);
};
</code></pre>

<p>我的 <code>model</code> 很简单,只有两个 <code>entities</code>,所以我对另一个 <code>Admin entity</code> 也使用相同的代码。这一切都很好,所有对象都被删除了,我可以通过执行另一个 <code>fetchRequest</code> 来确认这一点,它返回每个 <code>entity</code> 的对象计数 - 两者的计数都为零。当我在执行删除后尝试将数据保存回任一 <code>entity</code> 时,就会出现问题。 </p>

<p>带有上述代码的<code>ViewController</code> 是一个“Admin”控制屏幕,用户可以在其中登录并导出数据。所以当用户登录时,这里是要保存的代码:</p>

<pre><code>    // Save login details
    ;
    ;

    NSError *error;
    [ save:&amp;error];
</code></pre>

<p>然后我执行上面的 <code>fetchRequest</code> 并在按下“导出”按钮时导出所有数据。完成后,当我尝试登录同一个 <code>ViewController</code> 时,输出为:</p>

<pre><code>2014-10-27 12:43:49.653 NGLS &lt;NSManagedObject: 0x7a8c2460&gt; (entity: Admin; id: 0x7a82e3e0 &lt;x-coredata://3C9F3807-E314-439C-8B73-3D4459F85156/Admin/p30&gt; ; data: &lt;fault&gt;)
</code></pre>

<p>如果我导航回另一个 <code>ViewController</code>(使用我的 <code>navigation controller</code>),然后返回“Admin”控制屏幕并尝试再次登录,我得到了这个输出:</p>

<pre><code>2014-10-27 12:44:04.530 NGLS *** Terminating app due to uncaught exception &#39;NSObjectInaccessibleException&#39;, reason: &#39;CoreData could not fulfill a fault for &#39;0x7a82e3e0 &lt;x-coredata://3C9F3807-E314-439C-8B73-3D4459F85156/Admin/p30&gt;&#39;&#39;
</code></pre>

<p>(如果需要,我可以发布完整的日志)。</p>

<p>我尝试了很多方法来解决这个问题。核心数据很复杂,我不太明白我需要做什么来解决这个问题。我试图删除 <code>persistentStore</code> 并再次创建它,与 <code>managedObjectContext</code> 相同,但我没有尝试过任何工作。我在 <code>AppDelegate</code> 中实现了一个 <code>resetStore</code> 方法来删​​除和重建存储,如下所示:</p>

<pre><code>- (void)resetStores {
    NSError *error;
    NSURL *storeURL = [ URLForPersistentStore:[[ persistentStores] lastObject]];
    // lock the current context
    ;
    ;//to drop pending changes
    //delete the store from the current managedObjectContext
    if ([ removePersistentStore:[[ persistentStores] lastObject] error:&amp;error])
    {
      // remove the file containing the data
      [ removeItemAtURL:storeURL error:&amp;error];
      //recreate the store like in theappDelegate method
      [ addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&amp;error];//recreates the persistent store
    }
    ;
}
</code></pre>

<p>也试过这个方法:</p>

<pre><code>- (NSPersistentStoreCoordinator *)resetPersistentStore
{
    NSError *error = nil;
    if ( == nil)
      return ;

    _managedObjectContext = nil;

    NSPersistentStore *store = [ lastObject];

    if (!) {
      NSLog(@&#34;Unresolved error %@, %@&#34;, error, );
      abort();
    }

    // Delete file
    if ([ fileExistsAtPath:store.URL.path]) {
      if (![ removeItemAtPath:store.URL.path error:&amp;error]) {
            NSLog(@&#34;Unresolved error %@, %@&#34;, error, );
            abort();
      }
    }

    // Delete the reference to non-existing store
    _persistentStoreCoordinator = nil;
    NSPersistentStoreCoordinator *r = ;

    return r;
}
</code></pre>

<p>但这些都不起作用。我发现工作是在导出完成后,通过关闭并重新打开应用程序,一切都恢复正常。我试图弄清楚在关闭/打开与核心数据有关的应用程序时会发生什么过程,但我只是不知道要寻找什么。我在 Stack Overflow 上研究了 <em>许多</em> 问题并尝试了所有解决方案,但对我没有任何效果。我真的需要一些帮助,否则我将不得不在导出完成后强制用户退出应用程序 <code>exit(0);</code> 命令(因为它没有被提交到 App Store,它适用于内部员工)虽然我不想要那个解决方案,但肯定有一种方法可以让我重置我的数据库并继续使用该应用程序,而不必每次都关闭它。提前致谢。</p>

<p>引用文献:<br/>
<a href="https://stackoverflow.com/a/22630726/3107564" rel="noreferrer noopener nofollow">Deleting all records from Core Data</a> <br/>
<a href="https://stackoverflow.com/a/4436522/3107564" rel="noreferrer noopener nofollow">Reset a Core Data persistent store</a> <br/>
<a href="https://stackoverflow.com/a/8467628/3107564" rel="noreferrer noopener nofollow">How do I delete all objects from my persistent store in Core Data</a> <br/></p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>我已经设法通过简单地刷新 View 来解决这个问题。通过在导出完成后调用我的 <code>viewDidLoad</code> 方法,我创建了一个可以正常使用的新 <code>managedObject</code>,而无需离开该 <code>ViewController</code> 或退出应用程序完全一致。</p>

<pre><code>- (void)viewDidLoad
{
    ;
    // Do any additional setup after loading the view from its nib

    // Create fetchRequest
    NGLSAppDelegate *appDelegate = (NGLSAppDelegate *)[delegate];
    NSManagedObjectContext *context = ;
    NSFetchRequest *fetchRequest = [ init];
    NSEntityDescription *entity = ;
    ;

    NSError *error = nil;
    NSArray *fetchedObjects = ;

    // Fetch last object
    Model *admin = ;

    // Populate login fields with last stored details
    if (admin.userLogin == nil) {
      //NSLog(@&#34;Login empty&#34;);
    } else {
      self.usernameField.text = admin.userLogin;
      self.siteLocationField.text = admin.siteLocation;
    }

    // Create new managed object using the Admin entity description
    NSManagedObject *ManagedObjectAdmin;
    ManagedObjectAdmin = [NSEntityDescription insertNewObjectForEntityForName:@&#34;Admin&#34;
                                                       inManagedObjectContext:context];
    // Declare managed object
    self.managedObjectAdmin = ManagedObjectAdmin;

    // Save context
    NSError *saveError = nil;
    ;

// ... more stuff
}
</code></pre>

<p>解决方案一直都很简单。我会留下这个问题/答案,以便其他人在发现自己处于我的情况时可以从中受益。谢谢。</p>

<p>编辑:在导出后的任何地方重新创建 <code>managedObjectAdmin</code> 也可以,不需要调用 <code>viewDidLoad</code> 方法。导出完成后,我可以简单地创建新的 <code>managedObject</code> 并保存 <code>context</code> 并继续正常使用应用程序,而无需导航到另一个 <code>ViewController</code> 首先或重新启动应用程序。 </p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 重置 Core Data 模型中所有保存的数据,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/26588175/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/26588175/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 重置 Core Data 模型中所有保存的数据