15

我有一个使用 MagicalRecord 处理核心数据的应用程序,效果很好。但是我有不同的用户可以登录应用程序,当另一个用户登录时,必须清空核心数据数据库,以便不同的用户可以拥有自己的数据。数据库可以完全清空,因为数据也存储在网络服务上,因此在第一个用户再次登录后总是可以再次同步。

到目前为止,我似乎找不到用于此目的的辅助方法(有效)。我试过了

[MagicalRecord cleanUp];

每当用户注销时,但这并不能解决问题。

4

6 回答 6

38

我就是这样做的。必须有这条线:[MagicalRecord cleanup]. 没有它,[self setupDB]将无法工作。

更新:删除 -wal 和 -shm 文件。@thattyson 指出了 iOS 9 中的一个问题。另外,请参阅@onmyway133 的答案

- (void)setupDB
{
    [MagicalRecord setupCoreDataStackWithAutoMigratingSqliteStoreNamed:[self dbStore]];
}

- (NSString *)dbStore
{
    NSString *bundleID = (NSString *)[[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString *)kCFBundleIdentifierKey];
    return [NSString stringWithFormat:@"%@.sqlite", bundleID];
}

- (void)cleanAndResetupDB
{
    NSString *dbStore = [self dbStore];

    NSError *error1 = nil;
    NSError *error2 = nil;
    NSError *error3 = nil;

    NSURL *storeURL = [NSPersistentStore MR_urlForStoreName:dbStore];
    NSURL *walURL = [[storeURL URLByDeletingPathExtension] URLByAppendingPathExtension:@"sqlite-wal"];
    NSURL *shmURL = [[storeURL URLByDeletingPathExtension] URLByAppendingPathExtension:@"sqlite-shm"];

    [MagicalRecord cleanUp];

    if([[NSFileManager defaultManager] removeItemAtURL:storeURL error:&error1] && [[NSFileManager defaultManager] removeItemAtURL:walURL error:&error2] && [[NSFileManager defaultManager] removeItemAtURL:shmURL error:&error3]){
        [self setupDB];
    }
    else{
        NSLog(@"An error has occurred while deleting %@", dbStore);
        NSLog(@"Error1 description: %@", error1.description);
        NSLog(@"Error2 description: %@", error2.description);
        NSLog(@"Error3 description: %@", error3.description);
    }
}

这是斯威夫特版本:

func setupDB() {
    MagicalRecord.setupCoreDataStackWithAutoMigratingSqliteStoreNamed(self.dbStore())
}

func dbStore() -> String {
    return "\(self.bundleID()).sqlite"
}

func bundleID() -> String {
    return NSBundle.mainBundle().bundleIdentifier!
}

func cleanAndResetupDB() {
    let dbStore = self.dbStore()

    let url = NSPersistentStore.MR_urlForStoreName(dbStore)
    let walURL = url.URLByDeletingPathExtension?.URLByAppendingPathExtension("sqlite-wal")
    let shmURL = url.URLByDeletingPathExtension?.URLByAppendingPathExtension("sqlite-shm")

    var removeError: NSError?

    MagicalRecord.cleanUp()

    //Swift 1
    //let deleteSuccess = NSFileManager.defaultManager().removeItemAtURL(url, error: &removeError)

    //Swift 2
    let deleteSuccess: Bool
    do {
        try NSFileManager.defaultManager().removeItemAtURL(url)
        try NSFileManager.defaultManager().removeItemAtURL(walURL!)
        try NSFileManager.defaultManager().removeItemAtURL(shmURL!)
        deleteSuccess = true
    } catch let error as NSError {
        removeError = error
        deleteSuccess = false
    }

    if deleteSuccess {
        self.setupDB()
    } else {
        println("An error has occured while deleting \(dbStore)")
        println("Error description: \(removeError?.description)")
    }
}
于 2013-08-02T09:24:01.113 回答
20

为了扩展@yoninja 的答案,这将显式重置 CoreData 堆栈,并处理 wal 和 shm 文件

- (void)setupDB
{
    [MagicalRecord setDefaultModelNamed:@"Model.momd"];
    [MagicalRecord setupCoreDataStack];
}

- (void)cleanAndResetupDB
{
    [MagicalRecord cleanUp];

    NSString *dbStore = [MagicalRecord defaultStoreName];

    NSURL *storeURL = [NSPersistentStore MR_urlForStoreName:dbStore];
    NSURL *walURL = [[storeURL URLByDeletingPathExtension] URLByAppendingPathExtension:@"sqlite-wal"];
    NSURL *shmURL = [[storeURL URLByDeletingPathExtension] URLByAppendingPathExtension:@"sqlite-shm"];

    NSError *error = nil;
    BOOL result = YES;

    for (NSURL *url in @[storeURL, walURL, shmURL]) {
        if ([[NSFileManager defaultManager] fileExistsAtPath:url.path]) {
            result = [[NSFileManager defaultManager] removeItemAtURL:url error:&error];
        }
    }

    if (result) {
        [self setupDB];
    } else {
        NSLog(@"An error has occurred while deleting %@ error %@", dbStore, error);
    }
}
于 2014-08-09T15:56:28.093 回答
18

MagicalRecord 不为您提供此功能。该cleanUp方法提供给您在内存中重新初始化 CoreData 堆栈并清理任何上下文、队列和其他相关对象。但是,鉴于 MagicalRecord 确实提供了一种方便的方法来获取库的路径,因此自己动手并不难。

查看-[NSPersistentStore MR_urlForStoreName:]方法。这将为您提供商店的文件网址。然后,您可以使用NSFileManager实例将其删除。在设置 Core Data 堆栈之前要小心执行此操作,否则在保存时会崩溃,因为您会从正确初始化的堆栈下拉出存储。

于 2012-12-28T16:58:18.380 回答
5

下面将彻底删除 MagicalRecord CoreData sqlite 文件,以及 -wal 和 -shm 文件。MagicalRecord 将它们全部放在 Library 文件夹中;这只会从文件夹中删除所有文件。如果您需要将其他数据保留在 Library 文件夹中,这将不起作用,我没有:

- (void)resetCoreDataDB
{
    [MagicalRecord cleanUp];
    [self deleteFilesInLibrary];
    [MagicalRecord setupCoreDataStackWithAutoMigratingSqliteStoreNamed:@"YourDBName.sqlite"];
}

- (void)deleteFilesInLibraryDirectory
{
    NSString* folderPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSError *error = nil;
    for (NSString *file in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:folderPath error:&error])
    {
        [[NSFileManager defaultManager] removeItemAtPath:[folderPath stringByAppendingPathComponent:file] error:&error];
        if(error)
        {
            NSLog(@"Delete error: %@", error.description);
        }
    }
}
于 2014-07-29T13:10:29.660 回答
2

如果您使用 iOS 模拟器并删除了数据库文件,您可能会注意到数据仍然存在。但是,如果在实际设备上进行测试(应该是这样),则文件将被删除,并且上下文将按原样重置。

[MagicalRecord cleanUp];

// delete database file
NSError *error;
NSURL *fileURL = [NSPersistentStore MR_urlForStoreName:@"db.sqlite"];
[[NSFileManager defaultManager] removeItemAtURL:fileURL error:&error];
if(error) {
    // Hanldle error
}

// reset setup.
[MagicalRecord setupCoreDataStackWithAutoMigratingSqliteStoreNamed:@"db.sqlite"];
于 2014-01-10T01:26:44.883 回答
0

@yoninja 为Swift 4重写的答案:

private var dbStore : String? {
    get {
        if let bundleId = Bundle.main.bundleIdentifier {
            return bundleId + ".sqlite"
        }
        return MagicalRecord.defaultStoreName()
    }
}

func setupCoreDataStack() {
    MagicalRecord.setupCoreDataStack(withAutoMigratingSqliteStoreNamed: self.dbStore)
}

func cleanUp() {        
    MagicalRecord.cleanUp()

    var removeError: NSError?
    let deleteSuccess: Bool
    do {
        guard let url = NSPersistentStore.mr_url(forStoreName: self.dbStore) else {
            return
        }
        let walUrl = url.deletingPathExtension().appendingPathExtension("sqlite-wal")
        let shmUrl = url.deletingPathExtension().appendingPathExtension("sqlite-shm")

        try FileManager.default.removeItem(at: url)
        try FileManager.default.removeItem(at: walUrl)
        try FileManager.default.removeItem(at: shmUrl)

        deleteSuccess = true
    } catch let error as NSError {
        removeError = error
        deleteSuccess = false
    }

    if deleteSuccess {
        self.setupCoreDataStack()
    } else {
        print("An error has occured while deleting \(self.dbStore)")
        print("Error description: \(removeError.debugDescription)")
    }
}
于 2018-01-18T08:48:22.337 回答