Better way to convert NSArray of NSNumbers to array of NSStrings

孤者浪人 提交于 2019-11-27 05:57:20

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/8119043/better-way-to-convert-nsarray-of-nsnumbers-to-array-of-nsstrings

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