使用下标访问值和在NSDictionary中仅使用valueForKey之间的区别

时间:2016-10-07 16:41:21

标签: ios objective-c nsdictionary

我有以下一行:

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

但我想我可以通过这种方式使用订阅缩小这一行:

_driverName.text = responseDictionary[@"response" ][@"driverinfo"][@"name"];
它似乎更干净,更易读。 是否可以应用此语法而不会产生附带后果? 提前谢谢

1 个答案:

答案 0 :(得分:2)

忽略对distance的滥用(使用select user.id, user.fname, user.lname, user.email from `order` as o inner join payments on o.id = payments.order_id inner join user on o.user_id = user.id where o.orderplaced_ts > "2016-08-01 00:00:00" and o.store_id = 6 and o.order_status != "Cancelled" and payments.payment_method = "Cash" and not in (select 1 from payments pym where pym.orderid = o.id and o.id = user.id and pym.payment_method <> 'Cash') group by user.id ),您不应该在问题中使用任何一个示例。当你遇到问题时,两者都无法调试,因为数据结构不是你想象的那样。

虽然需要更多时间,但最终将每次访问拆分为一个单独的行是值得的:

valueForKey:

但是使用现代下标语法总是比使用objectForKey:更容易且更不容易出错,并且它确保您不会错误地使用NSDictionary *response = responseDictionary[@"response"]; NSDictionary *driverInfo = response[@"driverInfo"]; _driverName.text = driverInfo[@"name"];