Bracket syntax in Objective-C

3 Solutions Collect From Internet About “Bracket syntax in Objective-C”

It’s called object subscripting, as explained here

Its syntactic sugar, as


gets translated by the compiler to

[newSectionsArray objectAtIndexedSubscript:index];

NSDictionary implements subscripting too, so you can access an element in this fashion:


The cool (and potentially dangerous) feature is that this is generalized, so you can even have it on your own classes.

You just need to implement a couple of methods

(for indexed access)

- (id)objectAtIndexedSubscript:(NSUInteger)idx;
- (void)setObject:(id)obj atIndexedSubscript:(NSUInteger)idx;

or (for keyed access)

- (id)objectForKeyedSubscript:(id)key;
- (void)setObject:(id)obj forKeyedSubscript:(id)idx;

and you they will be called whenever you use bracket notation on the instances of you custom class.

So you could end up coding a grid-based game and accessing the elements on the grid by

board[@"B42"]; // => [board objectForKeyedSubscript:@"B42"]

or moving a piece on the board by

board[@"C42"] = @"Troll"; => [board setObject:@"Troll" forKeyedSubscript:@"C42"];

Nice, but I wouldn’t abuse of it.

That’s literal syntax, introduced in Clang 3.4. You could however use the old syntax [newSectionsArray objectAtIndex:index]. it’s the same thing.

newSectionsArray is probably an array (i.e. a contigous block of multiple objects of the same type) and index an integer. newSectionsArray[index] gives you the object at position index (starting counting with 0).