什么可以导致NSUserDefaults被清除

时间:2014-04-18 15:56:24

标签: ios iphone ios7 nsuserdefaults

我的应用程序收到了一些奇怪的报告,其中存储在NSUserDefaults中的应用程序设置正在被清除。这些报告都是在iOS 7s上进行的

我知道您可以通过卸载或拨打

来手动清除NSUserDefaults
NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];

[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];

但有没有其他已知原因让应用程序清除其设置?

1 个答案:

答案 0 :(得分:1)

如果您不想删除数据,则应使用KeyChain存储值。入门的好方法:Using KeyChain

下面我将提供一个示例代码,如何从KeyChain中存储和获取数据

导入所需的框架

#import <Security/Security.h>

将值存储到KeyChain

NSString *key = @"Full Name";
NSString *value = @"Steve Jobs";
NSData *valueData = [value dataUsingEncoding:NSUTF8StringEncoding];
NSString *service = [[NSBundle mainBundle] bundleIdentifier];
NSDictionary *secItem = @{
                              (__bridge id)kSecClass : (__bridge id)kSecClassGenericPassword, (__bridge id)kSecAttrService : service,
                              (__bridge id)kSecAttrAccount : key,
                              (__bridge id)kSecValueData : valueData,
                              };
    CFTypeRef result = NULL;
    OSStatus status = SecItemAdd((__bridge CFDictionaryRef)secItem, &result);
if (status == errSecSuccess)
{
     NSLog(@"Successfully stored the value");
}
else{
     NSLog(@"Failed to store the value with code: %ld", (long)status);
}

从KeyChain

获取值
NSString *keyToSearchFor = @"Full Name";
NSString *service = [[NSBundle mainBundle] bundleIdentifier];
NSDictionary *query = @{
                        (__bridge id)kSecClass : (__bridge id)kSecClassGenericPassword, (__bridge id)kSecAttrService : service,(__bridge id)kSecAttrAccount : keyToSearchFor,
                        (__bridge id)kSecReturnAttributes : (__bridge id)kCFBooleanTrue, };
CFDictionaryRef valueAttributes = NULL;
OSStatus results = SecItemCopyMatching((__bridge CFDictionaryRef)query,
                                       (CFTypeRef *)&valueAttributes);
NSDictionary *attributes =
(__bridge_transfer NSDictionary *)valueAttributes;
if (results == errSecSuccess){
    NSString *key, *accessGroup, *creationDate, *modifiedDate, *service;
    key = attributes[(__bridge id)kSecAttrAccount];
    accessGroup = attributes[(__bridge id)kSecAttrAccessGroup]; creationDate = attributes[(__bridge id)kSecAttrCreationDate]; modifiedDate = attributes[(__bridge id)kSecAttrModificationDate]; service = attributes[(__bridge id)kSecAttrService];
    NSLog(@"Key = %@\n \ Access Group = %@\n \
          Creation Date = %@\n \
          Modification Date = %@\n \
          Service = %@", key, accessGroup, creationDate, modifiedDate, service);
}
else
{
    NSLog(@"Error happened with code: %ld", (long)results);
}