views:

766

answers:

1

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

+5  A: 

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