在项目中用到了UUID,需要在用户第一次安装以后再次安装时UUID不会再变化,作为一个唯一的标识,就这个问题找了一些资料,记录下来以便下次使用。
简介
参考来源 http://www.tuicool.com/articles/Ir63UbI
UUID解决方案主要采用了keychain存储的解决方案,我们知道如果使用NSUserDefaults来存储的话当卸载以后数据也将会一并删除,目前最好的解决方案就是使用keychain存储。
创建keychain

创建完以后会自动生成一个entitlements文件

自定义存储类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| #import "INKeyChainStore.h" @implementation INKeyChainStore + (NSMutableDictionary *)getKeychainQuery:(NSString *)service { return [NSMutableDictionary dictionaryWithObjectsAndKeys: (id)kSecClassGenericPassword,(id)kSecClass, service, (id)kSecAttrService, service, (id)kSecAttrAccount, (id)kSecAttrAccessibleAfterFirstUnlock,(id)kSecAttrAccessible, nil]; }
+ (void)save:(NSString *)service data:(id)data { NSMutableDictionary *keychainQuery = [self getKeychainQuery:service]; SecItemDelete((CFDictionaryRef)keychainQuery);
[keychainQuery setObject:[NSKeyedArchiver archivedDataWithRootObject:data] forKey:(id)kSecValueData]; SecItemAdd((CFDictionaryRef)keychainQuery, NULL); }
+ (id)load:(NSString *)service { id ret = nil; NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];
[keychainQuery setObject:(id)kCFBooleanTrue forKey:(id)kSecReturnData]; [keychainQuery setObject:(id)kSecMatchLimitOne forKey:(id)kSecMatchLimit]; CFDataRef keyData = NULL; if (SecItemCopyMatching((CFDictionaryRef)keychainQuery, (CFTypeRef *)&keyData) == noErr) { @try { ret = [NSKeyedUnarchiver unarchiveObjectWithData:(__bridge NSData *)keyData]; } @catch (NSException *e) {
} @finally {
} } if (keyData) CFRelease(keyData); return ret; }
+ (void)deleteKeyData:(NSString *)service { NSMutableDictionary *keychainQuery = [self getKeychainQuery:service]; SecItemDelete((CFDictionaryRef)keychainQuery); }
@end
|
自定义一个类来获取UUID
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| + (NSString *)getUUID { NSString * strUUID = (NSString *)[INKeyChainStore load:@"uuid.yaowen"];
if ([strUUID isEqualToString:@""] || !strUUID) { CFUUIDRef uuidRef = CFUUIDCreate(kCFAllocatorDefault); strUUID = (NSString *)CFBridgingRelease(CFUUIDCreateString (kCFAllocatorDefault,uuidRef)); strUUID = [strUUID stringByReplacingOccurrencesOfString:@"-" withString:@""]; [INKeyChainStore save:@"uuid.yaowen" data:strUUID]; } return strUUID; }
|