Best way to generate NSData object with random bytes of a specific length?

Bama91 picture Bama91 · Feb 7, 2011 · Viewed 19k times · Source

If I create a new NSData object of a specific size using dataWithBytes:length:, what is the most efficient way to create the input bytes (20 Mb worth) of random characters, preferably without reading the data in from a file? I need a unique buffer of a specific size each time.

Thanks

Answer

Thomson Comer picture Thomson Comer · Feb 7, 2011

You can create a 20*2^20b NSData object, then append a random 4 byte integer to it 20*2^20/4 times with arc4random(). I believe you need to include stdlib.h (via Generating random numbers in Objective-C).

#include <stdlib.h>

-(NSData*)create20mbRandomNSData
{
  int twentyMb           = 20971520;
  NSMutableData* theData = [NSMutableData dataWithCapacity:twentyMb];
  for( unsigned int i = 0 ; i < twentyMb/4 ; ++i )
  { 
    u_int32_t randomBits = arc4random();
    [theData appendBytes:(void*)&randomBits length:4];
  }
  return theData;
}