将数据保存到本地,APP被删除,保存数据不会被删除

首先要导入这个 框架
#import


代码如下
+ (NSMutableDictionary *)getKeychainQuery:(NSString *)service {

return [NSMutableDictionary dictionaryWithObjectsAndKeys:

(id)kSecClassGenericPassword,(id)kSecClass,

service, (id)kSecAttrService,

service, (id)kSecAttrAccount,

(id)kSecAttrAccessibleAfterFirstUnlock,(id)kSecAttrAccessible,

nil];

}




+ (void)saveKey:(NSString *)serviceKey dataValue:(id)dataValue{

//Get search dictionary

NSMutableDictionary *keychainQuery = [self getKeychainQuery:serviceKey];

//Delete old item before add new item

SecItemDelete((CFDictionaryRef)keychainQuery);

//Add new object to search dictionary(Attention:the data format)

[keychainQuery setObject:[NSKeyedArchiver archivedDataWithRootObject:dataValue] forKey:(id)kSecValueData];

//Add item to keychain with the search dictionary

SecItemAdd((CFDictionaryRef)keychainQuery, NULL);

}




+ (id)loadValue:(NSString *)serviceKey{

id ret = nil;

【将数据保存到本地,APP被删除,保存数据不会被删除】NSMutableDictionary *keychainQuery = [self getKeychainQuery:serviceKey];

//Configure the search setting

//Since in our simple case we are expecting only a single attribute to be returned (the password) we can set the attribute kSecReturnData to kCFBooleanTrue

[keychainQuery setObject:(id)kCFBooleanTrue forKey:(id)kSecReturnData];

[keychainQuery setObject:(id)kSecMatchLimitOne forKey:(id)kSecMatchLimit];

CFDataRef keyData = https://www.it610.com/article/NULL;

if (SecItemCopyMatching((CFDictionaryRef)keychainQuery, (CFTypeRef *)&keyData) == noErr) {

@try {

ret = [NSKeyedUnarchiver unarchiveObjectWithData:(NSData *)keyData];

} @catch (NSException *e) {

NSLog(@"Unarchive of %@ failed: %@", serviceKey, e);

} @finally {

}

}

if (keyData)

CFRelease(keyData);

return ret;

}




+ (void)deleteValue:(NSString *)serviceKey {

NSMutableDictionary *keychainQuery = [self getKeychainQuery:serviceKey];

SecItemDelete((CFDictionaryRef)keychainQuery);

}

    推荐阅读