清除CoreData和所有内部 [英] Clearing CoreData and all that inside

查看:122
本文介绍了清除CoreData和所有内部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对CoreData和这个使用它的应用程序很新。
当我注销应用程序时,我目前正在处理一个清除整个核心数据的功能。



我有2个sqllite文件原因他们认为很方便)



如何清除所有数据的两个文件并将其重置为无数据状态?



我尝试了很多方法,按照SO的指南。



如何清除/重置所有CoreData在一对多的关系中



如何从Core Data中删除所有对象



他们似乎都失败了。
现在我想知道我做错了什么?也许有人可以解释我如何重置我的2 CoreData文件正确的方式。



编辑:

  //应清除整个coredata数据库。主要用于注销机制
- (void)resetCoreData
{
for(NSPersistentStore * store in self.persistentStoreCoordinator.persistentStores)
{
// NSPersistentStore * store = self.persistentStoreCoordinator.persistentStores [0];
NSError * error;
NSURL * storeURL = store.URL;
DLog(@storeURL:%@,storeURL);
NSPersistentStoreCoordinator * storeCoordinator = self.persistentStoreCoordinator;
[storeCoordinator removePersistentStore:store错误:&错误];
[[NSFileManager defaultManager] removeItemAtPath:storeURL.path error:& error];

DLog(@有erreurs:%@,错误);
// [self addDefaultData];
}

_persistentStoreCoordinator = nil;
_managedObjectContext = nil;
_managedObjectModel = nil;
}

这似乎不能清除我的CoreData。



EDIT2:

   - (NSManagedObjectContext *)managedObjectContext 
{
if(_managedObjectContext!= nil){
return _managedObjectContext;
}

NSPersistentStoreCoordinator * coordinator = [self persistentStoreCoordinator];
if(coordinator!= nil){
_managedObjectContext = [[NSManagedObjectContext alloc] init];
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
}
return _managedObjectContext;
}

- (NSManagedObjectModel *)managedObjectModel
{
if(__managedObjectModel!= nil){
return __managedObjectModel;
}

NSURL * modelURL = [[NSBundle mainBundle] URLForResource:@MyNamewithExtension:@momd];
__managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];

return __managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {

if(__persistentStoreCoordinator!= nil){
return __persistentStoreCoordinator;
}

NSString * storePath = [[self applicationDocumentsDirectory] ​​

stringByAppendingPathComponent:@MyName.sqlite];

NSFileManager * fileManager = [NSFileManager defaultManager];

//如果预期的存储不存在,请复制默认存储。
if(![fileManager fileExistsAtPath:storePath]){
NSString * defaultStorePath = [[NSBundle mainBundle] pathForResource:@MyNameofType:@momd];
if(defaultStorePath){

[fileManager copyItemAtPath:defaultStorePath toPath:storePath error:NULL];

}

}



__persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];

//检查当前模型的版本。如果是> = 2.0,
//然后只检查是否已执行迁移...
NSSet * versionIdentifiers = [[self managedObjectModel] versionIdentifiers];
DLog(@当前版本是我们的.xcdatamodeld文件设置为?%@,versionIdentifiers);

if([versionIdentifiers containsObject:@2.0])
{
BOOL hasMigrated = YES;
if(hasMigrated == YES){
storePath = nil;
storePath = [[self applicationDocumentsDirectory] ​​
stringByAppendingPathComponent:@MyName2.sqlite];

}
}

NSURL * storeUrl = [NSURL fileURLWithPath:storePath];
NSError * error;
NSDictionary * pscOptions = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:NO],NSInferMappingModelAutomaticallyOption,
nil];

if(![__ persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:storeUrl
options:pscOptions
error:& error]){
DLog(@未解析的错误%@,%@,错误,[错误userInfo]);
abort();
}

return __persistentStoreCoordinator;
}






编辑3:
我仍​​然在寻找一种方法来重置我的CoreData,如果我删除了整个应用程序并重新启动它。这样做的通常的方式不是为我的情况工作。还有2个sqllite文件。有一些迁移在应用程序的某个点发生的提示,但我不太确定什么时候和如何。错误日志显示没有用。



我不是寻找最有效的方法。只要方法。



帮助我,赏金是你的。



编辑4:
最终结果:
似乎我的旧代码有一个实例化的第二个ManagedObjectContext。这一刻,我检索了它,并与它做flush函数。两个sqlite文件都消失了,因为需要。



感谢所有努力在我的问题。

尝试以下方法来刷新数据库,它对我来说是完美的。

   - void)flushDatabase {
[__managedObjectContext lock];
NSArray * stores = [__persistentStoreCoordinator persistentStores];
for(NSPersistentStore * store in stores){
[__persistentStoreCoordinator removePersistentStore:store error:nil];
[[NSFileManager defaultManager] removeItemAtPath:store.URL.path error:nil];
}
[__managedObjectContext unlock];
__managedObjectModel = nil;
__managedObjectContext = nil;
__persistentStoreCoordinator = nil;
}


I'm pretty new to CoreData and this app that uses it. And I'm currently working on a feature that clears the entire core data when I log out in the app.

I have 2 sqllite files (for some reason they thought that was handy)

How can I clear both files of all data and reset them into a dataless state?

I've tried a lot of ways, following guides, on SO.

How to clear/reset all CoreData in one-to-many realationship

how to remove all objects from Core Data

They all seem to fail for me. Now I'm wondering what do I do wrong? And perhaps someone can explain me how to reset my 2 CoreData files the proper way.

EDIT:

//should clear the whole coredata database. mainly used for logout mechanism
-(void)resetCoreData
{
    for (NSPersistentStore *store in self.persistentStoreCoordinator.persistentStores)
    {
//    NSPersistentStore *store = self.persistentStoreCoordinator.persistentStores[0];
        NSError *error;
        NSURL *storeURL = store.URL;
        DLog(@"storeURL: %@", storeURL);
        NSPersistentStoreCoordinator *storeCoordinator = self.persistentStoreCoordinator;
        [storeCoordinator removePersistentStore:store error:&error];
        [[NSFileManager defaultManager] removeItemAtPath:storeURL.path error:&error];

        DLog(@"There are erreurs: %@", error);
//    [self addDefaultData];
    }

    _persistentStoreCoordinator = nil;
    _managedObjectContext = nil;
    _managedObjectModel = nil;
}

This doesn't seem to clear the CoreData for me.

EDIT2:

- (NSManagedObjectContext *)managedObjectContext
{
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        _managedObjectContext = [[NSManagedObjectContext alloc] init];
        [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return _managedObjectContext;
}

- (NSManagedObjectModel *)managedObjectModel
{
    if (__managedObjectModel != nil) {
        return __managedObjectModel;
    }

    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"MyName" withExtension:@"momd"];
    __managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];

    return __managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {

    if (__persistentStoreCoordinator != nil) {
        return __persistentStoreCoordinator;
    }

    NSString *storePath = [[self applicationDocumentsDirectory]

                           stringByAppendingPathComponent:@"MyName.sqlite"];

    NSFileManager *fileManager = [NSFileManager defaultManager];

    // If the expected store doesn't exist, copy the default store.
    if (![fileManager fileExistsAtPath:storePath]) {
        NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:@"MyName" ofType:@"momd"];
        if (defaultStorePath) {

            [fileManager copyItemAtPath:defaultStorePath toPath:storePath error:NULL];

        }

    }



    __persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: [self managedObjectModel]];

    //Check to see what version of the current model we're in. If it's >= 2.0,
    //then and ONLY then check if migration has been performed...
    NSSet *versionIdentifiers = [[self managedObjectModel] versionIdentifiers];
    DLog(@"Which Current Version is our .xcdatamodeld file set to? %@", versionIdentifiers);

    if ([versionIdentifiers containsObject:@"2.0"])
    {
        BOOL hasMigrated = YES;
        if (hasMigrated==YES) {
            storePath = nil;
            storePath = [[self applicationDocumentsDirectory]
                         stringByAppendingPathComponent:@"MyName2.sqlite"];

        }
    }

    NSURL *storeUrl = [NSURL fileURLWithPath:storePath];
    NSError *error;
    NSDictionary *pscOptions = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
                                [NSNumber numberWithBool:NO], NSInferMappingModelAutomaticallyOption,
                                nil];

    if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
                                                    configuration:nil
                                                              URL:storeUrl
                                                          options:pscOptions
                                                            error:&error]) {
        DLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    return __persistentStoreCoordinator;
}


Edit 3: I'm still looking for a way to reset my CoreData as if I deleted the entire app and started it up again. The usual ways of doing so are not working for my case. And there are 2 sqllite files. There are hints of a migration that took place at some point in the application but I'm not too sure when and how. Error logs show nothing useful.

I'm not looking for the most efficient way. Just the way.

Help me out and the bounty is yours.

Edit 4: FINAL RESULT: It seemed my legacy code had a second ManagedObjectContext instantiated. The moment I retrieved it and did the flush-function with it. Both sqlite-files disappeared as was needed.

Thanks to all that put effort in my problem.

解决方案

try the following method to flush the database, it works perfect for me.

-(void) flushDatabase{
    [__managedObjectContext lock];
    NSArray *stores = [__persistentStoreCoordinator persistentStores];
    for(NSPersistentStore *store in stores) {
       [__persistentStoreCoordinator removePersistentStore:store error:nil];
       [[NSFileManager defaultManager] removeItemAtPath:store.URL.path error:nil];
    }
    [__managedObjectContext unlock];
    __managedObjectModel    = nil;
    __managedObjectContext  = nil;
    __persistentStoreCoordinator = nil;
}

这篇关于清除CoreData和所有内部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆