Thinking in Javascript but writing Objective-C (Xcode/iOS): Arrays


This is a very simple comparison of creating arrays in Javascript vs Objective-C and follows the post on functions and methods along the same lines.

If we want to create a simple array in Javascript we can do so like this:

    var objectsArray = ["red","blue","green"];

To do the same thing in Xcode we write:


    NSArray *objectsArray = [[NSArray allocinitWithObjects:@"red"@"green"@"blue",       nil];
    // This creates an array, the last item of which must be nil - this isn't actually part of the array, it just tells the array to end


When we want to access a member of the array in Javascript we write, for example:

    var secondObjectInArray = objectsArray[1];

In Xcode we could write something like this:


  NSString *secondObjectInArray = [objectsArray objectAtIndex:1];
  // The NSString *secondObjectInArray is arbitrary and if the object wasn't a string we    wouldn't do this. We'd also most likely use introspection to find out exactly what kind of object it was we were dealing with


If we would like to change an item or add one to a Javascript array we do this:

    objectsArray[3] = "yellow";

This is something we can't do to an NSArray but we can do it to an NSMutableArray, and so we need to do this:


    NSMutableArray *moreObjects = [objectsArray mutableCopy];
    // create a mutable copy, i.e. one that can be added to or changed
    [moreObjects addObject:@"yellow"];


In order to return to an immutable NSArray to protect the contents from being erroneously changed by another pointer to the array being created, simply do this:


   objectsArray = [moreObjects copy];

Comments