Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to convert NSArray of NSNumbers to array of NSStrings

I have an NSArray consisting of NSNumbers and I want to convert this to an NSArray of NSStrings, by getting the stringValue of each NSNumber in the first array.

The method that comes to my mind is iterating each value in the first one, getting its string value and adding it into another array. But there should be a more elegant solution for this. Do you know one?

like image 472
aslisabanci Avatar asked Nov 14 '11 08:11

aslisabanci


1 Answers

NSArray implements the Key-Value Coding method valueForKey: in such a way that it returns a new array. The new array contains the results of asking each object in the original array for the specified value. In this case, NSNumber has its stringValue, so all you have to do is:

NSArray * b = [a valueForKey:@"stringValue"];

Plain old fast enumeration (or enumerateObjectsUsingBlock:) wouldn't be a terrible solution, though. NSArray's implementation of valueForKey: most likely uses a for loop internally, and that would be pretty readily understood by anyone who reads it later.

like image 54
jscs Avatar answered Oct 21 '22 00:10

jscs