Next: 2.5 Accessing Objects in Up: 2 NSArray Previous: 2.3 NSArrays are immutable

2.4 arrayWithObjects

To create an NSArray, you usually use the class method +arrayWithObjects:, which takes as arguments a nil-terminated list of objects to put in the array:
NSArray *names;

names = [NSArray arrayWithObjects: @"Nicola", @"Margherita",
                                   @"Luciano", @"Silvia", nil];
The last element in the list must be nil, to mark the end of the list. You can put in the same array objects of different classes:
NSArray *objects;
NSButton *buttonOne;
NSButton *buttonTwo;
NSTextField *textField;

buttonOne = AUTORELEASE ([NSButton new]);
buttonTwo = AUTORELEASE ([NSButton new]);
textField = AUTORELEASE ([NSTextField new]);

objects = [NSArray arrayWithObjects: buttonOne, buttonTwo, 
                                     textField, nil];
but you can't put nil inside an array. All objects in an array must be valid, not-nil objects.

When an object is put in an array, the NSArray sends to it a -retain message, to prevent it from being deallocated while it is still in the array. When an object is removed from the array (because the array is a NSMutableArray so objects can be removed from it, or because the array itself is deallocated), it is sent a -release message.



2008-01-16