Now that we’ve gone through the introductory course on Xcode and Objective-C, it’s time to drill down on some of the finer points in the language. In this lesson, we’ll be taking a look at arrays and strings, and how they differ from their AS3 counterparts.

Arrays in Objective-C

Just like Array in AS3, NSArray is your go-to solution for indexed lists of objects in Objective-C. Also, like AS3, the contents of arrays are NOT strict-typed, so you can mix and match whatever you want in your indexed list. (Sorry, there’s no Objective-C equivalent to Vectors.) However, since the novel square-bracket syntax has been so delicately shoved down our throats, there isn’t many options left for shorthand operations with Objective-C arrays. For example:

var arr:Array = [10, 20, 30, 40, 50];
var num:int = arr[2];

becomes

NSArray *arr = [NSArray arrayWithObjects:10, 20, 30, 40, 50, nil];
NSInteger num = [arr objectAtIndex:2];

A bit annoying, but whatever. You may also notice that the “arrayWithObjects” call also has a nil appended to the end. The nil is Objective-C’s version of NULL, and is required when defining a list of objects for an array. (The reason being is a bunch of boring stuff that has to do with compatibility to the native C layer.) Additionally, methods must be used not only for array instantiation, but also for retrieving values from an array. Luckily, for loops still translate elegantly, as shown below.

Actionscript 3.0:

for each(var obj:* in arr) {
    // do something with obj
}

Objective-C:

for(NSObject *obj in arr) {
    // do something with obj
}

Ok, so far so good, so where’s the WTF in this article? Well here it is: Arrays are, by default, immutable. This means that once the array is instantiated, it cannot be modified. Truthfully, this is a really nice feature. You can share arrays between classes without concern of unwarranted modification of the data, which can cause unexpected bugs in your code. But what if you want to modify an array? This is where NSMutableArray comes into play. NSMutableArray is a mutable subclass of NSArray, and adds your typical push and pop methods (named “addObject” and “removeLastObject,” respectively), as well as plenty of other features.

Mutable vs Immutable

Like I said before, immutable is a great way to share data sets between classes, but how do you compromise stricter data control with a necessary ability to modify the data internally? In Objective-C, it’s surprisingly simple to translate an object between its mutable and immutable forms. Take a look at this example:

NSMutableArray *marr = [[NSMutableArray alloc] init];
[marr addObject:10];
[marr addObject:20];
[marr addObject:30];
NSArray *arr = [NSArray arrayWithArray:marr];

Here we start with a mutable array, populate it as necessary, then convert it to an immutable array. Now we can just pass the immutable array to our other classes and sleep easy at night, knowing there won’t be any malicious 40s or 50s being pushed into our precious list. If we’re not doing any meticulous modifications to the array, we might even opt to do something like this:

NSArray *arr = [NSArray arrayWithObjects:10, 20, nil];
arr = [arr arrayByAddingObject:30];

If we have a preexisting array, we can replace it with a brand new one with one of its several convenience methods. Whatever option you choose, its preferable to structure your classes such that they communicate with immutable arrays as a lower common denominator of mutable arrays.

Associative Arrays

In AS3, associative arrays come in two flavors: Object and Dictionary. Object would use a key/value pair where the key is a string and value is whatever you want, while Dictionary allowed you to use anything for the keys and values. In Objective-C, despite having both an NSObject and NSDictionary, only the dictionary can truly be utilized as an associative array. NSObject is not dynamic, and therefore cannot have its “keys” defined as runtime properties. NSDictionary also has a subclass, NSMutableDictionary, which, as you might guess, means that the standard dictionary is immutable. Not much to talk about here otherwise, so I’m just going to put an example down here for you:

NSMutableDictionary *mdictionary = [[NSMutableDictionary alloc] init];
[mdictionary setObject:0 forKey:@"Number of effs I give on this example"];
NSDictionary *dictionary = [NSDictionary dictionaryWithDictionary:mdictionary];

Oh and also there’s NSMapTable, which is like NSMutableDictionary, except you can do some fancy stuff like more advanced memory options. Although both can handle keys that are more complex than just strings, map tables are a bit more elegant on your resources.

Sets

Finally, it’s worth noting that Objective-C also has something foreign to AS3, called sets. If arrays are ordered lists, sets are unordered lists. As such, data in sets can’t be directly accessed via indexes. Sets are slower at adding data than arrays, but are much faster at enumerating. Sets also require that all objects passed to it are unique. As you might have caught on at this point, the class names should be NSSet and NSMutableSet. Additionally, there’s NSCountedSet, which is also mutable, but lets you pass objects that are not unique to the set.

Tagged with:
 

5 Responses to Flex to Objective-C: 8-Data Lists

  1. csgo beta says:

    Hi, you’re welcome. Thx a lot for the tutorial =)

  2. Matt says:

    Should this:

    [dictionary setObject:0 forKey:@"Number of effs I give on this example"];

    be the mutable dictionary?

    [mdictionary setObject:0 forKey:@"Number of effs I give on this example"];

    Seems like you’re calling a method on an object that hasn’t been defined yet.

    Thanks for the blog post. This series is great!

  3. tom says:

    Thanks for the tutorials, I’ve found them really useful! Any chance, that youll continue to update them? I’d be really interested in custom itemrenderers in tables, and more stuff about layouts.

    • Steve says:

      I gotta stop declaring my return from hiatus. It makes me look bad when I don’t actually post afterwards… haha. Unfortunately I’ve had less time to blog ever since I started a full-time gig, but I do have plans to get back into it when things die down a bit. Thanks for following!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">

Set your Twitter account name in your settings to use the TwitterBar Section.