Sometimes we need to generate a random string will meet the needs of the project, which is now described a method (using Apple's own library);
First, import the header files in the project
//这是导入了所有加密库的头文件
#import <CommonCrypto/CommonCrypto.h>
//如果只是使用random函数,那么只要做如下导入即可
#import <CommonCrypto/CommonRandom.h>
Second, the use of function
//利用CCRandomGenerateBytes实现随机字符串的生成
- (NSString *)randomString:(NSInteger)length {
length = length/2;
unsigned char digest[length];
CCRNGStatus status = CCRandomGenerateBytes(digest, length);
NSString *s = nil;
if (status == kCCSuccess) {
s = [self stringFrom:digest length:length];
} else {
s = self;
}
NSLog(@"randomLength---:%@",s);
return s;
}
//将bytes转为字符串
- (NSString *)stringFrom:(unsigned char *)digest length:(NSInteger)leng {
NSMutableString *string = [NSMutableString string];
for (int i = 0; i < leng; i++) {
[string appendFormat:@"%02x",digest[i]];
}
NSLog(@"final stringFrom:%@",string);
return string;
}