Question

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?

Was it helpful?

Solution

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

OTHER TIPS

What you're noticing is not necessarily a variable name. Rather, it's a property (and the variable name that backs it up might be the same name or might be different, depending on the @synthesize for the property).

This allows unrelated classes to get access to properties of another class under defined circumstances, such as read-only, without needing to expose other parts of the class.

In Swift you can use #keyPath() to generate a key path string.

let keyPathString = #keyPath(BankAccount.accountBalance)

At compile time, the tokens inside the () will be checked as being a valid key path.

This is significantly better than writing your own key path string literals as the compilers will alert you to errors caused by typos or refactors.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top