简体   繁体   中英

iOS - CoreData deleting objects doesn't free disk space

I am deleting CoreData objects using this method:

    NSManagedObjectContext *theContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:nameEntity];
[fetchRequest setIncludesPropertyValues:NO]; //only fetch the managedObjectID
[fetchRequest setPredicate:predicate];
NSError *error;
NSArray *fetchedObjects = [theContext executeFetchRequest:fetchRequest error:&error];
for (NSManagedObject *object in fetchedObjects)
{
    [theContext deleteObject:object];
}

error = nil;
if(![theContext save:&error]){
    NSLog(@"Couldn't save: %@", error);
}

What I don't understand is that for instance I download data and store it, and in the Settings I can see that my app uses 5MB of disk space. Once I delete the data using this method, it says my app uses 6.3MB of data. That makes absolutely no sense at all. What am I doing wrong? Why isn't the data being deleted correctly?

When using the sqlite store, the storage is managed by sqlite, not the core data framework itself. When you delete a managed object, the row is deleted from the appropriate table. In a typical database, this does not result in freeing any disk space. As for why the space used might actually increase, this speculation on my part, but I think it's because of the transaction logging. Even though the transaction is complete, the log is not immediately purged.

I would recommend that you not worry about this. The sqlite library will have internal management to compact tables (reclaim space from deleted rows) and purge old transaction records.

You can open the core data store with the SQLite vacuum option set to reclaim disk space. Eg

NSDictionary *storeOptionsDict=@{NSSQLiteManualVacuumOption : @YES};
[persistentStoreCoordinator addPersistentStoreWithType: NSSQLiteStoreType configuration: nil URL: sourceStoreURL options: storeOptionsDict error: &error];

See this older question: How to VACUUM a Core Data SQLite db?

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