Initialize Array of Objects using NSArray

Howdy_McGee picture Howdy_McGee · Feb 20, 2013 · Viewed 156.9k times · Source

I'm pretty new to Objective-C and iOS so I've been playing around with the Picker View. I've defined a Person Class so that when you create a new Person it automatically gives that person a name and age.

#import "Person.h"

@implementation Person

@synthesize personName, age;

-(id)init
{
    self = [super init];
    if(self)
    {
        personName = [self randomName];
        age = [self randomAge];
    }

    return self;
}

-(NSString *) randomName
{
    NSString* name;
    NSArray* nameArr = [NSArray arrayWithObjects: @"Jill Valentine", @"Peter Griffin", @"Meg Griffin", @"Jack Lolwut",
                            @"Mike Roflcoptor", @"Cindy Woods", @"Jessica Windmill", @"Alexander The Great",
                            @"Sarah Peterson", @"Scott Scottland", @"Geoff Fanta", @"Amanda Pope", @"Michael Meyers",
                            @"Richard Biggus", @"Montey Python", @"Mike Wut", @"Fake Person", @"Chair",
                            nil];
    NSUInteger randomIndex = arc4random() % [nameArr count];
    name = [nameArr objectAtIndex: randomIndex];
    return name;
}

-(NSInteger *) randomAge
{
    //lowerBound + arc4random() % (upperBound - lowerBound);
    NSInteger* num = (NSInteger*)(1 + arc4random() % (99 - 1));

    return num;
}

@end

Now I want to make an array of Persons so I can throw a bunch into the picker, pick one Person and show their age. First though I need to make an array of Persons. How do I make an array of objects, initialize and allocate them?

Answer

Allen Zeng picture Allen Zeng · Feb 20, 2013

There is also a shorthand of doing this:

NSArray *persons = @[person1, person2, person3];

It's equivalent to

NSArray *persons = [NSArray arrayWithObjects:person1, person2, person3, nil];

As iiFreeman said, you still need to do proper memory management if you're not using ARC.