Search code examples
iosobjective-carraysnsarray

Initialize Array of Objects using NSArray


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?


Solution

  • NSMutableArray *persons = [NSMutableArray array];
    for (int i = 0; i < myPersonsCount; i++) {
       [persons addObject:[[Person alloc] init]];
    }
    NSArray *arrayOfPersons = [NSArray arrayWithArray:persons]; // if you want immutable array
    

    also you can reach this without using NSMutableArray:

    NSArray *persons = [NSArray array];
    for (int i = 0; i < myPersonsCount; i++) {
       persons = [persons arrayByAddingObject:[[Person alloc] init]];
    }
    

    One more thing - it's valid for ARC enabled environment, if you going to use it without ARC don't forget to add autoreleased objects into array!

    [persons addObject:[[[Person alloc] init] autorelease];