我的应用程序收到了一些奇怪的报告,其中存储在NSUserDefaults
中的应用程序设置正在被清除。这些报告都是在iOS 7s上进行的
我知道您可以通过卸载或拨打
来手动清除NSUserDefaults
NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
但有没有其他已知原因让应用程序清除其设置?
答案 0 :(得分:1)
如果您不想删除数据,则应使用KeyChain存储值。入门的好方法:Using KeyChain
下面我将提供一个示例代码,如何从KeyChain中存储和获取数据
#import <Security/Security.h>
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);
}
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);
}