2

I was reading Parse's iOS Developers Guide. I got confused where it shows PFObject assigning to keys with subscript syntax.

PFObject *gameScore = [PFObject objectWithClassName:@"GameScore"];
gameScore[@"score"] = @1337;
gameScore[@"playerName"] = @"Sean Plott";
gameScore[@"cheatMode"] = @NO;


PFObject *gameScore = [PFObject objectWithClassName:@"GameScore"];
gameScore[@"score"] = @1337;

First I thought that PFObject must be extending NSMutableDictionary, but PFObject is extending NSObject only. How it is behaving like NSMutableDictionary?

How can I do this for my own class?

jscs
  • 63,694
  • 13
  • 151
  • 195
Vivart
  • 14,900
  • 6
  • 36
  • 74

2 Answers2

4

NSHipster has the answer:

Similarly, custom-keyed subscripting can be added to your class by declaring and implementing these methods:

- (id)objectForKeyedSubscript:(*KeyType*)key;
- (void)setObject:(id)obj forKeyedSubscript:(*KeyType*)key;
Ben Pious
  • 4,765
  • 2
  • 22
  • 34
3

The syntax for setting a key value is translated by the compiler into a call to the method setObject:forKeyedSubscript and will work with any class that provides such a method, not just NSMutableDictionary.

For full details read "Object Indexing" in the Objective-C Literals section of the Clang compiler documentation.

HTH

CRD
  • 52,522
  • 5
  • 70
  • 86