Adding Array Subscripting To Your Classes in Objective-C

Xcode 4.4 added some great new literals syntax for collection classes and numbers, so now you can write NSArray *array = [@”one”, @”two”, @”three”]; And you can access those elements with array-style subscripting like this NSString *s = array[1];

On it own, that’s great, but there’s more under the surface here. When you write array[1], the compiler translates that into a method call named objectAtIndexSubscript:, which is implemented by NSArray. The cool part is that you can implement this method in your own classes, and then use subscripting on instances of your classes. You can also implement the sister method: setObject:atIndexedSubscript: to set values.

The code below is a simple example of how you could use this:

// Header

@interface ItemCollection : NSObject

@property (strong) NSMutableArray *list;

// Suport for Array-style subscripting. Ex. items[4] = @”hello”;

– (void)setObject:(id)anObject atIndexedSubscript:(NSUInteger)idx;

– (id)objectAtIndexedSubscript:(NSUInteger)idx;

@end

// Implementation

@implementation ItemCollection

– (void)setObject:(id)anObject atIndexedSubscript:(NSUInteger)idx {

self.list[idx] = anObject;

}

– (id)objectAtIndexedSubscript:(NSUInteger)idx {

return self.list[idx];

}

@end

// Using the class

ItemCollection *items = [ItemCollection new];

items[1] = @”boo”;

This is a contrived example, but with some imagination, you could find some cool uses for this to make your code more concise. Not only is this available for arrays, but you can use the key-value methods used by NSDictionary as well – objectForKeyedSubscript: and setObjectForKeyedSubscript:

You can read more about this here: http://clang.llvm.org/docs/ObjectiveCLiterals.html

Advertisements