Initialize Array of Objects using NSArray Initialize Array of Objects using NSArray arrays arrays

Initialize Array of Objects using NSArray


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.


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];


No one commenting on the randomAge method?

This is so awfully wrong, it couldn't be any wronger.

NSInteger is a primitive type - it is most likely typedef'd as int or long. In the randomAge method, you calculate a number from about 1 to 98.

Then you can cast that number to an NSNumber. You had to add a cast because the compiler gave you a warning that you didn't understand. That made the warning go away, but left you with an awful bug: That number was forced to be a pointer, so now you have a pointer to an integer somewhere in the first 100 bytes of memory.

If you access an NSInteger through the pointer, your program will crash. If you write through the pointer, your program will crash. If you put it into an array or dictionary, your program will crash.

Change it either to NSInteger or int, which is probably the best, or to NSNumber if you need an object for some reason. Then create the object by calling [NSNumber numberWithInteger:99] or whatever number you want.