从NSArray获取字符串值 [英] Getting the string value from a NSArray
问题描述
我有一个 NSArrayController
和我当我得到 selectedObjects
并创建一个NSString的值 valueForKey:@Name
它返回
I have a NSArrayController
and I when I get the selectedObjects
and create a NSString with the value of valueForKey:@"Name"
it returns
(
"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
推荐答案
当你在数组上调用 valueForKey:
> valueForKey:在数组中包含的每个元素,并返回这些值在一个新的数组,用 NSNull
替换任何 nil
值。也不需要从控制器复制 selectedObjects
数组,因为它是不可变的。
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"]);
如果 selectedObjects
中只有一个元素,数组,并且调用 valueForKey:
,它仍然会返回一个数组,但它将只包含数组中孤立元素的键的值。你可以使用 lastObject
来引用。
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);
这篇关于从NSArray获取字符串值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!