Generating Random Numbers, Strings and Data in Objective C

Today I’m open sourcing JFRandom, a powerful utility class for creating random numbers, arrays of these as well as random strings and data.  It’s available for free download over at github.

I’ve been using this class in my KEYBOX product for nearly a year now and I can attest to its robustness.  JFRandom works in both ARC and non-ARC projects for both iOS and OS X.

Whether you need random data for encryption purposes, video game AI, shuffled music playback or just lucky lotto ticket numbers, JFRandom has you covered.

 

How to Use JFRandom

JFRandom is very simple so I’ll just illustrate one-liner examples of the main functionality below.

 

For single random numbers…

NSInteger number = 0;
BOOL worked = [JFRandom generateNumberBetweenLow: 0 andHigh: 100 intoReceiver: &number];

 

For arrays of random numbers…

NSInteger sequence[100];
BOOL worked = [JFRandom generateNumberSequenceOfLength: 100 into: sequence betweenLow: -1000 andHigh: 1000 withOnlyUniqueValues: NO];

 

If you need each number in the array to also be unique do this…

NSInteger sequence[100];
BOOL worked = [JFRandom generateNumberSequenceOfLength: 100 into: sequence betweenLow: -1000 andHigh: 1000 withOnlyUniqueValues: YES];

Note that creating unique number arrays can cause performance issues as the existing selection must be first examined for instances of the next random number to place within.

 

JFRandom also generates random NSData instances…

NSData *data = [JFRandom generateRandomDataOfLength: 16];

 

If you need the bytes to be signed rather than unsigned…

NSData *data = [JFRandom generateRandomSignedDataOfLength: 16];

 

And of course if you need a string full of random characters it’s this easy…

NSString *text = [JFRandom generateRandomStringOfLength: 64];

 

These are the basic capabilities of JFRandom.  There are a few more methods that allow for randomly picking of numbers within a pre-determined array etc…  Check out JFRandom now and save yourself the trouble of coding and testing this yourself!

Comments are Disabled