replaceItemAtURL:withItemAtURL:backupItemName:options:resultingItemURL:error: broken in iOS 6?

Deadly 提交于 2019-12-06 10:11:53

The NSFileManager method replaceItemAtURL:withItemAtURL:backupItemName:options:resultingItemURL:error: is not a copy method; it is a move method. I.e., the file isn’t replaced with a copy of the replacement file, but with the replacement file itself. Since an app is not supposed to be able to modify its own bundle, the above code should never have worked in any version of iOS.

To retain atomicity, the solution is to first save a copy of the replacement file to the temporary directory, then replace the file with the copy in the temporary directory.

Here is the fixed test code:

NSError *error;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

NSString *sourcePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"txt"];
NSString *destinationPath = [documentsDirectory stringByAppendingPathComponent:@"test.txt"];

// Create initial file in documents directory
if (![fileManager fileExistsAtPath:destinationPath])
{
    BOOL fileCopied = [fileManager copyItemAtPath:sourcePath
                                           toPath:destinationPath
                                            error:&error];
    if (!fileCopied)
        [[self statusLabel] setText:[NSString stringWithFormat:@"Creation Error:\n\n%@", [error localizedDescription]]];
}

// Replace file in documents directory with copy of file from app bundle
if ([fileManager fileExistsAtPath:destinationPath])
{
    // Create temporary file
    NSString *tempPath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"test.txt"];

    BOOL tempCopied = [fileManager copyItemAtPath:sourcePath
                                           toPath:tempPath
                                            error:&error];
    if (!tempCopied)
        [[self statusLabel] setText:[NSString stringWithFormat:@"Temp Creation Error:\n\n%@", [error localizedDescription]]];

    // Replace file with temporary file
    NSURL *destinationURL = [NSURL fileURLWithPath:destinationPath];

    BOOL fileReplaced = [fileManager replaceItemAtURL:destinationURL
                                        withItemAtURL:[NSURL fileURLWithPath:tempPath]
                                       backupItemName:nil
                                              options:0
                                     resultingItemURL:&destinationURL
                                                error:&error];
    if (!fileReplaced)
        [[self statusLabel] setText:[NSString stringWithFormat:@"Replacement Error:\n\n%@", [error localizedDescription]]];
    else
        [[self statusLabel] setText:@"Successfully replaced file."];
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!