Getting the string value from a NSArray

旧城冷巷雨未停 提交于 2019-11-29 15:08:24

问题


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


回答1:


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);


来源:https://stackoverflow.com/questions/2068146/getting-the-string-value-from-a-nsarray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!