loa*_*ion 7 iphone nsuserdefaults ios ios7
我一直在为我的应用程序收到一些奇怪的报告,其中存储的应用程序设置NSUserDefaults正在被清除.这些报告都在iOS 7上
我知道您可以NSUserDefaults通过卸载或拨打电话来手动清除
NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
Run Code Online (Sandbox Code Playgroud)
但有没有其他已知的原因让应用程序清除其设置?
如果您不想删除数据,那么您应该使用 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);
}
Run Code Online (Sandbox Code Playgroud)
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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1516 次 |
| 最近记录: |