Here’s the code I came up with:
NSString *randomString = @"";
for (int x=0;x<NUMBER_OF_CHARS;x++) {
randomString = [randomString stringByAppendingFormat:@"%c", (char)(65 + (arc4random() % 25))];
}
return randomString;
EDIT:
To answer the comments:
1) I’m mostly concerned with brevity of code.
2) I also wonder if this is secure against guessing the string, and/or proof against collisions, if NUMBER_OF_CHARS is a high number (say 40) – not for this application, but in other cases.
3) Also, is there is a faster way if I want to make a ton of strings some day? This seems like it will be slow, since it makes an object each time through the loop.
If
NUMBER_OF_CHARSis compile-time constant, you can speed up your code by avoiding repeated object creation. You can make your program shorter by one line, too:As far as I know,
arc4random_uniformshould be good enough for cryptographic applications, but you may need to consult a cryptography expert if the data that you are planning to protect is of high value to you or especially to your clients.EDIT : Edited in response to nielsbot‘s comment.