Jesús Ayala Jesús Ayala - 1 month ago 6
Objective-C Question

Difference between accessing values using subscripting and using just valueForKey in NSDictionary

I have the following line:

_driverName.text = [[[responseDictionary valueForKey:@"response" ] valueForKey:@"driverinfo"]valueForKey:@"name"];


But I think I can shrink this line by using subscription in this way:

_driverName.text = responseDictionary[@"response" ][@"driverinfo"][@"name"];


it seems more clean and readable.
is it possible to apply this syntax without collateral consequences?
thanks in advance

Answer

Ignoring the misuse of valueForKey: (use objectForKey:), you should not use either example in your question. Both suffer from being impossible to debug when you run into issues because the data structure isn't what you thought it was.

While it takes more time, it is worth it in the end to split each access into a separate line:

NSDictionary *response = responseDictionary[@"response"];
NSDictionary *driverInfo = response[@"driverInfo"];
_driverName.text = driverInfo[@"name"];

But using the modern subscript syntax is always easier and less prone to error than using objectForKey: and it ensures you don't mistakenly use valueForKey:.