When switching to or beginning with Objective C you might be tempted to try to use the old c-style arrays, but that’s better left to the hard core C-enthusiasts. For programming Cocoa Touch we always use the NSArray class because of the additional intelligence it provides for us, not to mention integration with memory management.
The first thing I ever added into NSArray was string objects. And so will probably everybody who starts with Objective C.
NSString *someText = @"Static Text"; // static allocation NSString *someMoreText = [[NSString alloc] initWithString:@"More Static Text"]; // manually allocated NSArray *myArray = [NSArray arrayWithObjects:someText, someMoreText, nil]; // note the nil [someMoreText release]; // don't forget to release NSString *retrievedText = [myArray objectAtIndex:1]; // first index = 0 NSLog(retrievedText); |
How about numbers? Generally you can only add instances of objects into NSArray. But luckily Apple has created the NSNumber class which provides a container object for any kind of number, i.e. int, float or even BOOL.
int i=123; float f=5.0; NSNumber *num_i = [NSNumber numberWithInt:i]; NSNumber *num_f = [NSNumber numberWithFloat:f]; NSNumber *num_b = [NSNumber numberWithBool:YES]; NSArray *myArray = [NSArray arrayWithObjects:num_i, num_f, num_b, nil]; |
With the methods above you are able to add strings and numbers into arrays. There is yet another wrapper class that allows to put even more complex data types and structs into arrays: NSValue. Most usefully are the UIKit additions to NSValue which give you the possibility of packaging CGRect, CGPoint, CGAffineTransform or CGSize structs into objects. And those are just as easy to put into an array.
CGRect aRect = CGRectMake(0, 0, 100.0, 100.0); CGSize aSize = CGSizeMake(10.0, 20.0); NSValue *val_rect = [NSValue valueWithCGRect:aRect]; NSValue *val_size = [NSValue valueWithCGSize:aSize]; NSArray *myArray = [NSArray arrayWithObjects:val_rect, val_size, nil]; |
Soon you will find it odd that NSArray does not have any method to add and remove objects. The reason for this is that most standard objects are non-changable (aka “immutable”) as such. To gain such modification features you have to use the mutable cousin NSMutableArray. This gives you methods like addObject or removeObject.
NSMutableArray *myArray = [[NSMutableArray alloc] init]; [myArray addObject:@"first string"]; [myArray addObject:@"second string"]; [myArray addObject:@"third string"]; [myArray removeObjectAtIndex:1]; NSLog([myArray description]); // a quick way to show contents [myArray release]; |
NSArrays are the meat and bones of most Objective-C apps. Anybody trying to master this language has no way around them.
Categories: Recipes
Great explanation 🙂
It was a little confusing when I browsed through some other posts, but yours was the simplest
and straight forward !
Keep it up, thanks !