4

Like many of iOS developers I have encountered the issue with application crashing on system before 5.1 when using NSURLIsExcludedFromBackupKey.

It was well described how to evaluate existence of this key on this thread:

Use NSURLIsExcludedFromBackupKey without crashing on iOS 5.0

One of samvermette's comments says that there is a bug in iOS simulator.

Nevertheless I have encountered the same issue with a Release build, even in 2 separate applications. After some investigation I have discovered that application crashed even before main() method beeing called. Which hinted me that this is connected with

NSString * const NSURLIsExcludedFromBackupKey;

evaluation at application launch.

I am not an expert in this field, but I have found out that, if any reference to const value occurs in code (even if it is not actually accessed in runtime) this const is evaluated at very application launch. And this simply causes that crash that many of us experience.

I would like to ask you for some help. Maybe you know a way how to 'weakly' refer to a const value, or maybe there is specific compiler flag. (Using Apple LLVM 3.1).

Thanks in advance.

Please do not comments to put this const's value directly which is @"NSURLIsExcludedFromBackupKey" in this case. I am aware of this workaround, reson for this story is to find a general solution.

4

2 回答 2

1

您可以在 < 5.0.1 的系统上使用此代码

#include <sys/xattr.h>

- (BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL
{
    const char* filePath = [[URL path] fileSystemRepresentation];

    const char* attrName = "com.apple.MobileBackup";
    u_int8_t attrValue = 1;

    int result = setxattr(filePath, attrName, &attrValue, sizeof(attrValue), 0, 0);
    return result == 0;
}

在这里阅读更多。

编辑

如果您只是询问如何检查外部常量的可用性,您可以将其地址与 NULL 或 nil 进行比较。这是推荐的方法。

if (&NSURLIsExcludedFromBackupKey) {
    // The const is available
}
于 2012-05-17T12:33:22.280 回答
1

感谢https://stackoverflow.com/a/9620714/127493 ,我找到了解决方案!

NSString * const NSURLIsExcludedFromBackupKey;

与SDK 兼容性指南所说的不同,即使 Base SDK 设置为 iOS 5.1,也不是弱链接。

诀窍是使用这个 const 的结果。
如果我做

NSLog(@"%@", NSURLIsExcludedFromBackupKey);

结果是@"NSURLIsExcludedFromBackupKey"

所以我的结果代码是

#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)

NSError * error = nil;
BOOL success;
if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"5.1")) {
    success = [storeURL setResourceValue:[NSNumber numberWithBool:YES] forKey:@"NSURLIsExcludedFromBackupKey" error:&error];
}
于 2012-07-25T10:16:39.237 回答