Friday, May 6, 2011

NSArray creation example

Following code shows some basic NSArray creation examples.
You can see fiver other ways of creating NSArray objects.
NSArray is the most basic data structure (which is used for array and linked-list) in Apple's
objective C environment.


Code borrowed from http://www.icodeblog.com/2009/08/26/objective-c-tutorial-nsarray/


// I am using strings, but you can add just about any object to an NSArray
 
// Creates an NSArray with one object
NSArray  * myArray = [NSArray arrayWithObject:@"foo"];
 
// Creates an NSArray with multiple objects. Don't forget to add nil as the last object
NSArray  * myArray2 = [NSArray arrayWithObjects:@"foo",@"bar",@"baz",nil];
 
// Creates an NSArray from another NSArray
NSArray * myArray3 = [NSArray arrayWithArray:myArray2];
 
// This will create an NSArray from data on iCodeBlog.  Go ahead and try it out, this file exists on our servers and contains valid data.
NSArray * myArray4 = [NSArray arrayWithContentsOfURL:[NSURL URLWithString:@"http://my.own.url/foo.plist"]];
 
// Normal Initialization.
// 
NSArray * foo = [[NSArray alloc] initWithObjects:@"foo",@"bar",@"baz",nil];