Tuesday, 26 June 2012

Xcode Random Number (iOS & OSX)

There seems to be a lot a different ways to generate random numbers in Xcode when programming for iOS and/or OSX and a lot of people using some very complex method, which although are sometimes required, are usually overkill.

The simplest way I've found is arc4random(). All it requires it online line of code as follows:

ran = arc4random() % 50;

The number you specify, 50 in this case, will be the upper limit of your generation -1. So when 50 is defined you will generate numbers between 0 and 49.

A sample program (for command line in OSX):


//
//  main.m
//
//  Created by James Krawczyk on 27/06/2012.
//  Copyright (c) 2012 James Krawczyk. All rights reserved.
//

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{

    @autoreleasepool 
    {
        //Define integer variable to store random number in and initalize it
        int ran = 0;
        
        //Create random number between 0 and 49
        ran = arc4random() % 50;
        
        //Print result to log
        NSLog(@"Random Number: %i",ran);
    
    }
    return 0;
}




No comments:

Post a Comment