Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the string value from a NSArray

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

like image 986
nanochrome Avatar asked Jan 14 '10 22:01

nanochrome


People also ask

What's a difference between NSArray and NSSet?

The main difference is that NSArray is for an ordered collection and NSSet is for an unordered collection. There are several articles out there that talk about the difference in speed between the two, like this one. If you're iterating through an unordered collection, NSSet is great.

What is difference between NSArray and NSMutableArray?

The primary difference between NSArray and NSMutableArray is that a mutable array can be changed/modified after it has been allocated and initialized, whereas an immutable array, NSArray , cannot.

What is difference between array and NSArray in Swift?

Array is a struct, therefore it is a value type in Swift. NSArray is an immutable Objective C class, therefore it is a reference type in Swift and it is bridged to Array<AnyObject> . NSMutableArray is the mutable subclass of NSArray .

Can NSArray contain nil?

arrays can't contain nil. There is a special object, NSNull ( [NSNull null] ), that serves as a placeholder for nil.


1 Answers

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);
like image 169
dreamlax Avatar answered Sep 22 '22 19:09

dreamlax