简体   繁体   中英

Could not delete core data PersistentStore

I want to remove the app PersistentStore completely. I read the following question completely and none of them worked:

Delete/Reset all entries in Core Data?

I have a Model Helper and do the delete task inside it:

#import <CoreData/CoreData.h>

@interface GeneralModel : NSFetchedResultsController

@property (nonatomic, strong) NSManagedObjectContext *context;
@property (nonatomic, strong) NSManagedObjectModel *model;

- (NSString *)storagePath;
- (void)removeStorage;
- (void)removeStorage2;
@end

@implementation GeneralModel

- (instancetype)init
{
    self = [super init];
    if (self) {
        // Read in Model.xcdatamodeld
        _model = [NSManagedObjectModel mergedModelFromBundles:nil];
        NSPersistentStoreCoordinator *psc =
        [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:_model];

        // Where does the SQLite file go?
        NSString *path = self.storagePath;
        NSURL *storeURL = [NSURL fileURLWithPath:path];
        NSError *error = nil;
        if (![psc addPersistentStoreWithType:NSSQLiteStoreType
                               configuration:nil
                                         URL:storeURL
                                     options:nil
                                       error:&error]) {
            @throw [NSException exceptionWithName:@"OpenFailure"
                                           reason:[error localizedDescription]
                                         userInfo:nil];
        }

        // Create the managed object context
        _context = [[NSManagedObjectContext alloc] init];
        _context.persistentStoreCoordinator = psc;

    }
    return self;
}

- (NSString *)storagePath
{
    NSArray *documentDirectories =
    NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                        NSUserDomainMask,
                                        YES);
    // Get one and only document directory from that list
    NSString *documentDirectory = [documentDirectories firstObject];
    return [documentDirectory stringByAppendingPathComponent:@"model.sqlite"];
}

- (void)removeStorage {

    NSPersistentStore *store = [self.context.persistentStoreCoordinator.persistentStores lastObject];
    NSError *error = nil;
    NSURL *storeURL = store.URL;
    BOOL isRemovePersistentStore = [self.context.persistentStoreCoordinator removePersistentStore:store error:&error];
    if (isRemovePersistentStore == NO) {
        NSLog(@"NO RemovePersistentStore. Reason: %@", error.localizedFailureReason);
    }

    BOOL isRemoveItemAtURL = [[NSFileManager defaultManager] removeItemAtURL:storeURL error:&error];
    if (isRemoveItemAtURL == NO) {
        NSLog(@"NO RemoveItemAtURL. Reason: %@", error.localizedFailureReason);
    }
}

- (void)removeStorage2 {
     NSError *error;
     NSString *storagePath = [self storagePath];

     NSDictionary *options = @{NSPersistentStoreUbiquitousContentNameKey: @"model"};
     bool removeResult = [NSPersistentStoreCoordinator removeUbiquitousContentAndPersistentStoreAtURL:[NSURL URLWithString:storagePath] options:options error:&error];
     if (removeResult == NO) {
     NSLog(@"Could not remove Storage. Reason: %@", error.localizedFailureReason);
     }
}

@end

When I call the "removeStorage" method by the following code:

GeneralModel *model = [[GeneralModel alloc] init];
[model removeStorage];

Result is that No error apear in the console, but it just removed the main storage file: "model.sqlite" and 2 other related files: "model.sqlite-shm" and "model.sqlite-wal" remained.

When I call the "removeStorage2" method by the same code, I see the following text on the console and none of the files deleted:

Could not remove Storage. Reason: (null)

How could I solve this problem?

Check out the video " Straight outta Moscone Center West " for the official introduction of how you should be doing this, and/or consult NSPersistentStoreCoordinator.h from which the following snippet was extracted.

/* delete or truncate the target persistent store in accordance with the store
   class's requirements.  It is important to pass similar options as
   addPersistentStoreWithType: ... SQLite stores will honor file locks, journal
   files, journaling modes, and other intricacies.  It is not possible to unlink
   a database file safely out from underneath another thread or process, so this
   API performs a truncation.  Other stores will default to using NSFileManager.
 */
- (BOOL)destroyPersistentStoreAtURL:(NSURL *)url
                           withType:(NSString *)storeType
                            options:(nullable NSDictionary *)options
                              error:(NSError**)error NS_AVAILABLE(10_11, 9_0);

/* copy or overwrite the target persistent store in accordance with the store
   class's requirements.  It is important to pass similar options as
   addPersistentStoreWithType: ... SQLite stores will honor file locks, journal
   files, journaling modes, and other intricacies.  Other stores will default
   to using NSFileManager.
 */
- (BOOL)replacePersistentStoreAtURL:(NSURL *)destinationURL
                 destinationOptions:(nullable NSDictionary *)destinationOptions
         withPersistentStoreFromURL:(NSURL *)sourceURL
                      sourceOptions:(nullable NSDictionary *)sourceOptions
                          storeType:(NSString *)storeType
                              error:(NSError**)error NS_AVAILABLE(10_11, 9_0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM