美文网首页
iOS生成唯一UUID方法

iOS生成唯一UUID方法

作者: jazzfly | 来源:发表于2019-10-08 15:01 被阅读0次
//uuid  消息的唯一标识
+ (NSString *)uuidString

{
    CFUUIDRef uuid_ref = CFUUIDCreate(NULL);
    
    CFStringRef uuid_string_ref= CFUUIDCreateString(NULL, uuid_ref);
    
    NSString *uuid = [NSString stringWithString:(__bridge NSString *)uuid_string_ref];
    
    CFRelease(uuid_ref);
    
    CFRelease(uuid_string_ref);
    
    return [uuid lowercaseString];
}

通过时间戳生成UUID

-(NSString*) uuid {

    char data[10];
    
    for (int x=0;x<10;data[x++] = (char)('A' + (arc4random_uniform(26))));
    
    NSDate *  datenow=[NSDate date];
    
    NSString *ns_sendCount = [[NSUserDefaults standardUserDefaults] objectForKey:@"sendMessageCount"];
    int sendCount = [ns_sendCount intValue];
    NSDate *preSendTime = (NSDate *)[[NSUserDefaults standardUserDefaults] objectForKey:@"preSendTime"];
    
    if (preSendTime == nil)
    {
        [[NSUserDefaults standardUserDefaults] setObject:datenow forKey:@"preSendTime"];
    }
    else
    {
        NSCalendar *chineseClendar = [ [ NSCalendar alloc ] initWithCalendarIdentifier:NSGregorianCalendar];
        
        NSUInteger unitFlags =  NSHourCalendarUnit | NSMinuteCalendarUnit |NSSecondCalendarUnit | NSDayCalendarUnit| NSMonthCalendarUnit | NSYearCalendarUnit;
        
        NSDateComponents *DateComponent = [chineseClendar components:unitFlags fromDate:preSendTime toDate:datenow options:0];
        
        if ([DateComponent day] > 0)
        {
            [[NSUserDefaults standardUserDefaults] setObject:datenow forKey:@"preSendTime"];
            [[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:@"sendMessageCount"];
            sendCount = 0;
        }
        else
        {
            sendCount ++;
            [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%d",sendCount] forKey:@"sendMessageCount"];
        }
        
    }
    
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]];
    
    NSString * n_str = [NSString stringWithFormat:@"%@%@%@%@%@",
                        [[NSString alloc] initWithBytes:data length:10 encoding:NSUTF8StringEncoding]
                        ,@"-"
                        ,timeSp
                        ,@"-"
                        ,[NSString stringWithFormat:@"%d",sendCount]];
    
    return n_str;
}

相关文章

网友评论

      本文标题:iOS生成唯一UUID方法

      本文链接:https://www.haomeiwen.com/subject/lwnlyctx.html