Dissecting an NSArray

Objective-C is based on good old C.  It also has support for object oriented programming, such as classes, virtual methods, and lots of the goodies I’m accustomed to using in C#. One of the classes included in the Foundation library is NSArray.  It’s basically like a read-only ArrayList in the .NET Framework.

This is an array of strings, Objective-C style:

NSArray * array = [NSArray arrayWithObjects:@"Foo", @"Bar", nil];

For a .NET developer, that line of code might look pretty strange.  Let’s break it apart piece by piece so that it makes more sense.

  1. What’s up with that NS prefix on the type name?  It’s a remnant of NeXT Software’s API  from their NeXTStep operating system, which Mac OS X is based on.  You’ll find that Apple framework classes use all-caps prefixes all the time.
  2. The * means that the ‘array’ variable is a pointer to an NSArray object.  If you don’t know what a pointer is, I suggest you study up on it before getting into Objective-C much further.  It’s sort of like an object reference in .NET programming, in that it can be used to find an object in memory, but pointers can be used and abused in ways that references cannot (it’s beyond the scope of this post to review pointers).
  3. Those [brackets] following the assignment operator indicate that a message is being sent.  Sending a message is similar to, but not the same as, calling a method.  The end result of sending a message to an object, or a class in this case, is that a method will be invoked if the Objective-C message dispatcher can find a suitable method to invoke; otherwise it throws an error.  Also, if you send a message to nil (i.e. a null pointer) it does not crash your app.  It just does nothing and keeps on running.  In other words, method calls are mediated by a message dispatcher at runtime.  This helps the language be very flexible, at the cost of type safety.
  4. What’s that ‘arrayWithObjects:‘ all about?  That is the message being sent to the NSArray class.  It causes an immutable array to be created that contains whatever objects are in the parameter listing that follows the colon.
  5. Note the @ sign before each string.  That indicates the string is an NSString, instead of a C-style string.
  6. Last but not least, the final item in the array is nil.  That is required by NSArray, and other Foundation collection classes.  It basically just puts a zero (0) into the last slot of the array, so that other code can figure out where the array ends.

In case you’re wondering how to loop over the contents of the array, the following loop shows it in action.  It writes each string to the Console window.

for(NSString * s in array)
NSLog(@"%@", s);

Another point of interest is that the Foundation collection classes won’t let you put primitive C values (like an int or char) into them.  In C# you can add/remove a value type to/from a collection of object references, like ArrayList, because it automatically performs boxing and unboxing for you.  In Objective-C you must do that work yourself.  If you wanted to put, say, an integer into an NSArray, you would box it into an NSNumber object.

If you need to be able to add and remove items, NSArray is not the right collection to use. Instead you need to create an NSMutableArray, which is like an ArrayList in the .NET world.  We’ll explore that class in a future post.

I’m starting to enjoy Objective-C, despite how strange it seems to a hardened C# developer like myself.  I’ll keep you posted with other tidbits and etceteras and such as I keep learning more.  That’s enough for tonight.  Over and out.

This entry was posted in Objective-C. Bookmark the permalink.

11 Responses to Dissecting an NSArray

  1. Darren Oster says:

    And of course, don’t forget about NSMutableArray, NSArray’s mutable cousin. Many classes in Objective C have mutable equivalents (such as NSString / NSMutableString, etc).

    I gotta say, while .NET is still a brilliant platform and C# a wonderful language, I’m (so far) quite happy with Objective C for iOS development. (Not sure if I’ll ever get into OSX development, but the iPhone & iPad are just such compelling devices!)

  2. Joe says:

    I would be interested to hear (after a few weeks) if learning Objective C is work it – or is MonoTouch a better bet.
    By the looks of this, for me it looks like MonoTouch is the way to go. I do the occasional C++ development and it used to be my mother tongue, but Objective-C looks like it belongs in the 1990s.

    • Josh Smith says:

      I’m learning about MonoTouch for work. The book I’m reading about it has a chapter on Obj-C. The reason is, MonoTouch has an interop layer between C# and Obj-C, which enables you to call into the native platform (like P/Invoke for the iPhone). So I think it’s worth learning at least enough Obj-C to make use of the interop support, otherwise you won’t be able to take full advantage of MonoTouch. Kind of ironic, eh? 🙂


  3. Mark Smith says:

    Totally agree with WRT MonoTouch Josh.

    Not only will learning Objective-C help you with interop, there are so many samples out there (not to mention all the SDK docs and tutorials from Apple) that it’s almost a necessity. MonoTouch is great, I’ve used it several times now for building iOS applications, but at some point you run into a snag that requires some research and invariably the solution exists in some ObjC sample 🙂

    Plus, it gives you a better appreciation for MonoTouch’s brevity — consider the pinnacle example of trimming a string in ObjC:

    myString = [myString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];


    myString = myString.Trim(new char[] { ‘ ‘, ‘\r’, ‘\n’ });

  4. brad says:

    Amazing how much kludge that language/platform has…

    • Josh Smith says:

      You might be right, Brad. I don’t know enough about Objective-C and Cocoa yet to give a meaningful assessment.

  5. Pingback: Messages and methods in Objective-C | iJoshSmith

  6. Toby says:

    Actually, your point #6 is wrong. The nil is not put into the array. It’s used as a terminator for the NSArray initializer you are using. The “for” construct knows how many elements there are in the array (by sending it the “count” selector).

Comments are closed.