开发者

Better way to convert an NSArray of NSStrings to NSNumbers

开发者 https://www.devze.com 2023-01-10 19:52 出处:网络
Consider the following code NSString *param_string @\"1:3:6:10:15:22:28:30\"; NSArray *params = [param_string componentsSeparatedByString:@\":\"];

Consider the following code

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开发者_如何学JAVA] atIndex:i]];
}

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.

Thanks


How about this.

Add a category to NSString

@interface NSString(MyConverter)

-(NSDecimalNumber*) decimalNumberValue;

@end

@implementation NSString(MyConverter)

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

@end

Now you can do this

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

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

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.


NSString has an instance method intValue that might make this more straightforward.

NSNumber *value = [NSNumber numerWithInt:[[params objectAtIndex:i] intValue]];

Now insert that value into the array. If the string is always this simple, you really don't a number formatter.


You might use the NSScanner and avoid 2 loops (one inside componentsSeparatedByString and one that fills your mutable array).

With NSScanner you may accomplish your goal with one while and only one array (mutable array of numbers).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号