As an iOS developer with a basic experience in C++ I am comparing many features of the languages. I'm wondering why variable names in this sample snippet of code:
[bankInstance addObserver:personInstance
forKeyPath:@"accountBalance"
options:NSKeyValueObservingOptionNew
context:NULL];
are passed as a @"string", not by pointer for example?
That is a key path. It isn't necessarily a variable name; instead, it's a list of properties. In this case the list only has one item, but in other cases it might be something like @"account.balance.inDollars"
, where each element in the chain has its property looked up by name.
As for why you don't just write, say, account.balance.inDollars
— well, think about what that would do if you substituted it there. It would access the property when you set up the observer and pass the current value of the property. That isn't what we want. Instead, we want to tell the observation mechanism how to look up the property itself so it can watch for changes, and it does that with key-value coding. (This also allows you to set up bindings graphically in Interface Builder.)