我知道,关于这个话题存在很多问题,但是我将NSString保存到Keychain(使用ARC)时遇到了一些麻烦。
以下是我使用的代码:
+ (NSString *)getStringForKey:(NSString *)aKey
{
NSMutableDictionary *searchDictionary = [self DictionaryForKey:aKey];
NSString *stringValue;
[searchDictionary setObject:(__bridge id)kSecMatchLimitOne forKey:(__bridge id)kSecMatchLimit];
[searchDictionary setObject:(id)kCFBooleanTrue forKey:(__bridge id)kSecReturnData];
CFTypeRef result = NULL;
OSStatus statusCode = SecItemCopyMatching((__bridge CFDictionaryRef)searchDictionary, &result);
if (statusCode == errSecSuccess)
{
NSData *resultData = CFBridgingRelease(result);
stringValue =[[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding];
}
return stringValue;
}
+ (void)setString:(NSString *)string forKey:(NSString *)aKey
{
if (string != nil) {
NSData *encodedData = [string dataUsingEncoding:NSUTF8StringEncoding];
NSMutableDictionary *keyDictionary = [self DictionaryForKey:aKey];
[keyDictionary setObject:encodedData forKey:(__bridge id)kSecValueData];
SecItemAdd((__bridge CFDictionaryRef)keyDictionary, nil);
}
}
我发现有时候getStringForKey:
会返回nil(也许是1次100)。每次调用此方法时,配置文件都会显示内存泄漏。
我也尝试使用[NSKeyedUnarchiver unarchiveObjectWithData:]
,但同样的问题出现了 - NSKeyedUnarchiver
发生泄漏。
我想我错过了一些必不可少的东西。我跟着this guide但无法解决我的问题。请帮帮我:)