Search code examples
iosobjective-cmacosnsfilemanager

Unable to delete .zip file from file system


Unable to delete .zip file from file system.

Error:

NSError *error;
BOOL deleted = [[NSFileManager defaultManager] removeItemAtPath:[DocumentDirectory stringByAppendingPathComponent:[UserDefaults stringForKey:kNCSIOfflineDataFileName]] error:&error];
if (!deleted) {
    DebugLog(@"%s %@", __PRETTY_FUNCTION__, error);
}

Code:

NSError *error;
    BOOL deleted = [[NSFileManager defaultManager] removeItemAtPath:[UserDefaults stringForKey:kNCSIOfflineDataFilePath] error:&error];
    if (!deleted) {
        DebugLog(@"%s %@", __PRETTY_FUNCTION__, error);
    }

Path is verified: enter image description here


Solution

  • Storing file paths that include the absolute path to an app's documents folder in NSUserDefaults is a very bad idea.

    Here's why:

    1. The UUID of an app will change when it's updated.
    2. iOS will migrate the user defaults during the update.
    3. You load the old absolute value and it's no longer pointing to a file.

    Instead store just the values after the Documents file root and build the full path every time using NSSearchPathForDirectoriesInDomains.