Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

migratePersistentStore: causes duplicate data when destination URL exists

Just encountered a scenario that I thought I'd share. When using NSPersistentStoreCoordinator migratePersistentStore: with a destination URL that already exists, the resulting data is merged. My scenario is that I'm creating dated backups whenever my app closes and it's possible that multiple launches in the same day will backup so the same file.

like image 944
greg Avatar asked May 15 '26 06:05

greg


1 Answers

I solved the issue by using NSFileManager fileExistsAtPath: and removeItemAtPath: to remove the existing file before calling migratePersistentStore:. This seems to have solved the duplication issue.

I couldn't find documentation that this is a feature but maybe it is.

UPDATED

I've added some example code for Jim. The flag for disabling journal_mode was very important for my use case. See here for more info

if ([[NSFileManager defaultManager] fileExistsAtPath: backupPath])
    [[NSFileManager defaultManager] removeItemAtPath: backupPath
                                               error: nil];

return [BRManagedObject.persistentStoreCoordinator 
           migratePersistentStore: store
                            toURL: [NSURL fileURLWithPath: backupPath]
                          options: @{
                  NSSQLiteManualVacuumOption : @(YES)
#ifndef SQLITE_USES_WRITE_AHEAD_LOG
             ,    NSSQLitePragmasOption : @{ @"journal_mode" : @"DELETE" }
#endif
                                                                             }
                         withType: persistentStoreType
                            error: nil];
like image 190
greg Avatar answered May 19 '26 03:05

greg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!