Next: Accessing Objects in a Up: NSArray Previous: NSArrays are immutable

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.



Nicola 2002-01-13