objective-c 从 NSArray 获取字符串值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2068146/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting the string value from a NSArray
提问by nanochrome
I have a NSArrayControllerand I when I get the selectedObjectsand create a NSString with the value of valueForKey:@"Name"it returns
NSArrayController当我得到selectedObjects并创建一个 NSString 并valueForKey:@"Name"返回它的值时,我有一个和我
(
"This is still a work in progress "
)
and all I want to have is the text in the ""how would I get that? also, this my code:
我想要的只是""我如何得到它的文本?另外,这是我的代码:
NSArray *arrayWithSelectedObjects = [[NSArray alloc] initWithArray:[arrayController selectedObjects]];
NSString *nameFromArray = [NSString stringWithFormat:@"%@", [arrayWithSelectedObjects valueForKey:@"Name"]];
NSLog(@"%@", nameFromArray);
Edit: I also have other strings in the array
编辑:我在数组中还有其他字符串
回答by dreamlax
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 NSNullfor any nilvalues. There's also no need to duplicate the selectedObjectsarray from the controller because it is immutable anyway.
当您调用valueForKey:数组时,它会调用数组中valueForKey:包含的每个元素,并在新数组中返回这些值,并替换NSNull任何nil值。也不需要selectedObjects从控制器复制数组,因为它无论如何都是不可变的。
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 selectedObjectsarray, 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.
如果selectedObjects数组中只有一个元素,并且您调用valueForKey:,它仍然会返回一个数组,但它只会包含数组中唯一元素的键的值。您可以使用lastObject.
NSString *theName = [[[arrayController selectedObjects] valueForKey:@"name"] lastObject];
NSLog (@"%@", theName);

