本文介绍了将NSStrings的NSArray转换为NSNumbers的更好方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码

NSString *param_string @"1:3:6:10:15:22:28:30";
NSArray *params = [param_string componentsSeparatedByString:@":"];

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterNoStyle];

NSMutableArray *convertedArray = [[NSMutableArray alloc] initWithCapacity:[params count]];

for(int i = 0; i < [params count]; i++){
    [convertedArray insertObject:[formatter numberFromString:[params objectAtIndex:i] atIndex:i]];
}

是否有更好,更有效的方法来实现这一目标?最初的param_string在实践中可能会更长,但是我不希望在params数组中有大约200个以上的元素.

Is there a better, more efficient way of achieving this? The initial param_string could be longer in practice but I don't expect there to ever be more than approximately 200 elements in the params array.

谢谢

推荐答案

如何?

为NSString添加类别

Add a category to NSString

@interface NSString(MyConverter)

-(NSDecimalNumber*) decimalNumberValue;

@end

@implementation NSString(MyConverter)

-(NSDecimalNumber*) decimalNumberValue
{
    return [NSDecimalNumber decimalNumberWithString: self];
}

@end

现在您可以这样做

NSString *param_string @"1:3:6:10:15:22:28:30";
NSArray *params = [param_string componentsSeparatedByString:@":"];

NSArray* decimalNumbers = [params valueForKey: @"decimalNumberValue"];

很显然,如果您想要除NSDecimalNumber之外的其他对象,只需相应地更改类别.该方法只需要返回一个可以放在数组中的对象即可.

Clearly if you want some other object than a NSDecimalNumber, just alter your category accordingly. The method just has to return an object that can be put in an array.

这篇关于将NSStrings的NSArray转换为NSNumbers的更好方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 01:33