直接访问Objective-C中的嵌套字典值 [英] Directly accessing nested dictionary values in Objective-C
问题描述
有没有办法直接访问Objective-C中外部数组的内部数组?例如,对外部数据源的调用返回以下对象:
Is there a way to directly access an inner-array of an an outer array in Objective-C? For example, a call to an external data source returns the following object:
{
bio = "this is the profile.bio data";
"first_name" = John;
"last_name" = Doe;
location = {
name = "Any Town, Any State";
};
metadata = {
pictures = {
picture = "https://picture.mysite.com/picture.jpeg";
}
}
}
我想要能够访问,例如location.name或metadata.pictures.picture数据。然而,点符号似乎不起作用。例如:
I want to be able to access, for example, the location.name or the metadata.pictures.picture data. Dot notation, however, does not seem to work. For example:
_gfbLocation = [result objectForKey:@"location.name"];
_gfbPicture = [result objectForKey:@"metadata.pictures.picture"];
我能够访问这些数据的唯一方法是首先设置内部数组的内容对象
The only way I have been able to access this data is by first setting the contents of the inner arrays to objects. Thoughts?
推荐答案
对于这样的嵌套键,您可以使用 keyPath 。 keyPath只是一些连接点的键。您可以使用它们从支持键值编码的对象中检索嵌套值 - 包括像您这样的NSDictionary对象。所以在你的情况下,这应该工作:
For nested keys like that you can use a keyPath. A keyPath is just a series of keys joined with dots. You can use them to retrieve nested values from objects that support Key-Value Coding - including NSDictionary objects like yours. So in your case this should work:
[result valueForKeyPath:@"location.name"];
有关键值编码的更多详细信息,请参阅Apple的 ./apple.com / library / ios /#documentation / Cocoa / Conceptual / KeyValueCoding / KeyValueCoding.html%23 // apple_ref / doc / uid / 10000107irel =noreferrer
For more detail on Key-Value Coding, see Apple's Key-Value Coding Programming Guide.
另请参见这个相关的StackOverflow问题。
这篇关于直接访问Objective-C中的嵌套字典值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!