Tuesday, August 28, 2012

Generating a Random value in objective-c

Hi, today lets see how to generate a random number from zero to a given Number.


/ Get random value between 0 and 99
int x = arc4random() % 100;
 
// Get random number between 500 and 1000
int y =  (arc4random() % 501) + 500); 

Now Lets see how to Generate a random alpha numeric value.  This is usually required for genrating passwords/ IDs.

   NSString *letters = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

-(NSString *) genRandStringLength: (int) len {

    NSMutableString *randomString = [NSMutableString stringWithCapacity: len];

    for (int i=0; i<len; i++) {
         [randomString appendFormat: @"%C", [letters characterAtIndex: arc4random() % [letters length]]];
    }

    return randomString;
}

Getting Current Date into a String (ios)


Hi Lets see the simple code to get current time


  //Get current date
    NSDate *date = [NSDate date];
    // format it
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
    [dateFormat setDateFormat:@"MMM dd, yyyy"];
    // convert it to a string
    NSString *dateString = [dateFormat stringFromDate:date];
    // free up memory
    [dateFormat release];
  //Try it
    NSLog(@"Todays date is = %@",dateString);
This is what i got :
Todays date is = Aug 28, 2012

Cheers

Friday, August 24, 2012

initwitharray VS arrayWithObjects


InitWith Object Syntax:
NSArray *bar = [[NSArray alloc] initWithObjects:@"hai",@"how",@"are",@"you",nil];
Array With Objects Syntax:
NSArray *tempArray = [NSArray arrayWithObjects:@"hai",@"how",@"are",@"you",nil];

Result= return [[[NSArray alloc] initWithObjects:@"hai",@"how",@"are",@"you",nil] autorelease]
So here the array returned is auto-released. Thats the only difference.