0

I like to mess with coding every now and then as a hobby and I noticed an unfamiliar syntax in some of the Apple Developer documentation:

newSectionsArray[index]

I normally expect something like:

[object method]

Can anyone explain this to me?

Thanks!

Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235
Caborca87
  • 187
  • 1
  • 16

3 Answers3

4

It's called object subscripting, as explained here

Its syntactic sugar, as

newSectionsArray[index]

gets translated by the compiler to

[newSectionsArray objectAtIndexedSubscript:index];

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

dictionary[@"key"]

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.

Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235
1

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

Kyle Fang
  • 1,139
  • 6
  • 14
  • Objective-C 2.0 is ages old and came with 10.5. But it's a bit of a strange versioning convention anyways, internally we are at version 4-532.2, so far far away from 2.0 (but I guess evolutionary changes don't sell that well) – JustSid Sep 30 '13 at 06:46
  • @JustSid Sorry about that, I should have checked first. – Kyle Fang Sep 30 '13 at 06:47
0

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).

Oswald
  • 31,254
  • 3
  • 43
  • 68
  • `newSectionsArray` is in this case an `NSArray` or `NSMutableArray` and can store whatever object type (`id`) (they do **not** have to be of same type) ;) – HAS Sep 30 '13 at 08:39