Getting the string value from a NSArray

倾然丶 夕夏残阳落幕 提交于 2019-11-30 09:55:26

When you call valueForKey: on an array, it calls valueForKey: on each of the elements contained in the array, and returns those values in a new array, substituting NSNull for any nil values. There's also no need to duplicate the selectedObjects array from the controller because it is immutable anyway.

If you have multiple objects in your array controller's selected objects, and you want to see the value of the name key of all items in the selected objects, simply do:


NSArray *names = [[arrayController selectedObjects] valueForKey:@"name"];

for (id name in names)
    NSLog (@"%@", name);

Of course, you could print them all out at once if you did:

NSLog (@"%@", [[arrayController selectedObjects] valueForKey:@"name"]);

If there's only one element in the selectedObjects array, and you call valueForKey:, it will still return an array, but it will only contain the value of the key of the lone element in the array. You can reference this with lastObject.

NSString *theName = [[[arrayController selectedObjects] valueForKey:@"name"] lastObject];
NSLog (@"%@", theName);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!