gpt4 book ai didi

ios - 什么会导致 NSUserDefaults 被清除

转载 作者:可可西里 更新时间:2023-11-01 03:34:27 26 4
gpt4 key购买 nike

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

我知道您可以通过卸载或调用来手动清除 NSUserDefaults

NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];

[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];

但是否还有任何其他已知原因导致应用清除其设置?

最佳答案

如果您不想让您的数据被删除,那么您应该使用 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);
}

关于ios - 什么会导致 NSUserDefaults 被清除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23157670/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com