如何使用比较:选项对 NSArray 进行排序
我有一个 NSArray,其中包含数字作为 NSString 对象。 IE。
[array addObject:[NSString stringWithFormat:@"%d", 100]];
如何对数组进行数字排序?我可以使用 compare:options
并将 NSNumericSearch
指定为 NSStringCompareOptions
吗?请给我一个示例/示例代码。
I have an NSArray containing numbers as NSString objects. ie.
[array addObject:[NSString stringWithFormat:@"%d", 100]];
How do I sort the array numerically? Can I use compare:options
and specify NSNumericSearch
as NSStringCompareOptions
? Please give me an example/sample code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用为
sortedArrayUsingFunction:context:
方法也应该适用于 NSStrings,因为它们也有intValue
方法。You can use the example code given for the
sortedArrayUsingFunction:context:
method which should work fine for NSStrings too as they also have theintValue
method.由于您的对象是数字,因此您可以使用 NSNumber 对象(通过 stringValue 属性轻松转换为字符串),而不是使用 NSString 对象,并使用 sortedArrayUsingDescriptors:。
例如:
Since your objects are numbers, instead of using NSString objects, you could use NSNumber objects (easily turned into strings via the stringValue property) and sort the array using sortedArrayUsingDescriptors:.
For example: