美文网首页
iOS随机字符串(serial)

iOS随机字符串(serial)

作者: coder1003 | 来源:发表于2018-09-03 16:40 被阅读0次
//生成0-x之间的随机正整数
int value =arc4random_uniform(x + 1);

//生成随机正整数
int value = arc4random();

//通过arc4random() 获取0到x-1之间的整数的代码如下:
int value = arc4random() % x; 
 
//获取1到x之间的整数的代码如下: 
int value = (arc4random() % x) + 1; 
 
//最后如果想生成一个浮点数,可以在项目中定义如下宏:
#define ARC4RANDOM_MAX      0x100000000 
 
//然后就可以使用arc4random() 来获取0到100之间浮点数了(精度是rand()的两倍),代码如下:
double val = floorf(((double)arc4random() / ARC4RANDOM_MAX) * 100.0f);

随机字符串(根据自己需要长度设置kRandomLength值; UUIDString可取前两部分即可)

// 生成字符串长度
#define kRandomLength 10
- (NSString *)serial
{
    //1.UUIDString
    NSString *string = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    
    //2.时间戳
    NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
    NSString *timeStr = [NSString stringWithFormat:@"%.0f",time];
    
    //3.随机字符串kRandomLength位
    static const NSString *kRandomAlphabet = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    NSMutableString *randomString = [NSMutableString stringWithCapacity: kRandomLength];
    for (int i = 0; i < kRandomLength; i++) {
        [randomString appendFormat: @"%C", [kRandomAlphabet characterAtIndex:arc4random_uniform((u_int32_t)[kRandomAlphabet length])]];
    }
    
    //==> UUIDString去掉最后一项,再拼接上"时间戳"-"随机字符串kRandomLength位"
    NSMutableArray *array = [[NSMutableArray alloc] initWithArray:[string componentsSeparatedByString:@"-"]];
    [array removeLastObject];
    [array addObject:timeStr];
    [array addObject:randomString];
    return [array componentsJoinedByString:@"-"];
}

相关文章

网友评论

      本文标题:iOS随机字符串(serial)

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