使用NSURLIsExcludedFromBackupKey而不会在iOS 5.0上崩溃

sam*_*tte 13 iphone objective-c ios

检查可用性似乎工作正常,但我似乎无法设置NSURLIsExcludedFromBackupKey密钥而不会在启动时出现此崩溃:

dyld:未找到符号:_NSURLIsExcludedFromBackupKey引用自:/ Users/sam/Library/Application Support/iPhone Simulator/5.0/Applications/B0872A19-3230-481C-B5CE-D4BDE264FBDF/Transit.app/Transit预期:/ Applications/Xcode. app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator5.0.sdk/System/Library/Frameworks/Foundation.framework/Foundation in/Users/sam/Library/Application Support/iPhone Simulator/5.0/Applications /B0872A19-3230-481C-B5CE-D4BDE264FBDF/Transit.app/Transit

这是我的方法:

- (BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL {    
    if (&NSURLIsExcludedFromBackupKey == nil)
        return NO;

    NSError *error;
    [URL setResourceValue:[NSNumber numberWithBool:YES] forKey:NSURLIsExcludedFromBackupKey error:&error];
    return (error != nil);
}
Run Code Online (Sandbox Code Playgroud)

如果我注释掉这一行,崩溃就会消失:

[URL setResourceValue:[NSNumber numberWithBool:YES] forKey:NSURLIsExcludedFromBackupKey error:&error];
Run Code Online (Sandbox Code Playgroud)

我必须弱化基金会吗?

编辑:不确定它是否有所作为,但这种方法被放在一个NSFileManager类别中.

tim*_*tim 19

这是iOS <= 5.0.1和> = 5.1的代码,包括@Cocoanetics提到的迁移技术.

- (BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL
{
    const char* filePath = [[URL path] fileSystemRepresentation];
    const char* attrName = "com.apple.MobileBackup";
    if (&NSURLIsExcludedFromBackupKey == nil) {
        // iOS 5.0.1 and lower
        u_int8_t attrValue = 1;
        int result = setxattr(filePath, attrName, &attrValue, sizeof(attrValue), 0, 0);
        return result == 0;
    } else {
        // First try and remove the extended attribute if it is present
        int result = getxattr(filePath, attrName, NULL, sizeof(u_int8_t), 0, 0);
        if (result != -1) {
            // The attribute exists, we need to remove it
            int removeResult = removexattr(filePath, attrName, 0);
            if (removeResult == 0) {
                NSLog(@"Removed extended attribute on file %@", URL);
            }
        }

        // Set the new key
        return [URL setResourceValue:[NSNumber numberWithBool:YES] forKey:NSURLIsExcludedFromBackupKey error:nil];
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 你不应该使用错误来检测故障; 使用setResourceValue:forKey的BOOL:错误返回.Cocoa约定是错误在成功时可能包含某些内容(您应该忽略它). (3认同)
  • 我通过检测和删除属性来分享要点:https://gist.github.com/2002382 (2认同)

sam*_*tte 5

这似乎是iPhone 5.0模拟器的一个错误.我尝试在5.0设备上运行代码,没有崩溃.报告此错误为rdar:// 11017158.

编辑:这已在Xcode 4.5 DP2中修复(不确定它是否在4.4中).

  • 我可以确认在使用发布版本时它会在5.0.1设备上崩溃. (4认同)
  • 我担心问题不仅存在于模拟器上.构建Release版本时,我遇到了同样的崩溃.实际上一切都在模拟器上正常工作.我认为问题在于应用程序启动时的const评估,因为应用程序甚至在主方法调用之前就崩溃了. (3认同)