Vivart
Vivart

Reputation: 15313

How does PFObject allow subscripting like NSMutableDictionary?

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?

Upvotes: 2

Views: 66

Answers (2)

CRD
CRD

Reputation: 53000

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

Upvotes: 3

Ben Pious
Ben Pious

Reputation: 4805

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;

Upvotes: 4

Related Questions