個人解法
+(NSString*)getUUID {
NSUserDefaults* pref = [NSUserDefaults standardUserDefaults];
NSString* uuid = [pref stringForKey:LOG_KEY_UUID];
if (uuid == nil || [uuid length]<=0) {
CFUUIDRef uuidObject = CFUUIDCreate(kCFAllocatorDefault);
uuid = (__bridge_transfer NSString *)CFUUIDCreateString(kCFAllocatorDefault, uuidObject);
[pref setValue:uuid forKey:LOG_KEY_UUID] ;
[pref synchronize];
CFRelease(uuidObject);
}
return uuid;
}
官方解法
http://www.neatstudio.com/show-2040-1.shtml
- #define NEW_UUID_KEY @"uuid_created_by_developer"
- @interface NewUUID : NSObject {
- NSString *uuid;
- }
- + (NSString *)identifier;
- @property (nonatomic, retain) NSString *uuid;
- @end
- #import <Foundation/Foundation.h>
- #import "NewUUID.h"
- @implementation NewUUID
- @synthesize uuid;
- - (id)init {
- self = [super init];
- if (self) {
- uuid = NULL;
- return self;
- }
- return nil;
- }
- + (id)_instance {
- static id obj = nil;
- if( nil == obj ) {
- obj = [[self alloc] init];
- }
- return obj;
- }
- + (NSString *)identifier {
- NSUserDefaults *handler = [NSUserDefaults standardUserDefaults];
- [[NewUUID _instance] setUuid:[NSString stringWithFormat:@"%@", [handler objectForKey:NEW_UUID_KEY]]];
- if (NULL == [[NewUUID _instance] uuid] || 46 > [[[NewUUID _instance] uuid] length]) {
- CFUUIDRef uuid = CFUUIDCreate(NULL);
- CFStringRef uuidStr = CFUUIDCreateString(NULL, uuid);
- NSString *result = [NSString stringWithFormat:@"%@-%@", @"new-uuid-", uuidStr];
- CFRelease(uuidStr);
- CFRelease(uuid);
- [[NewUUID _instance] setUuid:result];
- [handler setObject:[[NewUUID _instance] uuid] forKey:NEW_UUID_KEY];
- [handler synchronize];
- }
- return [[NewUUID _instance] uuid];
- }
- @end
沒有留言:
張貼留言