2

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] 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

acqu13sce
  • 3,789
  • 4
  • 25
  • 32

3 Answers3

7

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.

JeremyP
  • 84,577
  • 15
  • 123
  • 161
  • Thank you, I like this solution, I'm still quite a fresh obj-c programmer and wasn't aware of the valueForKey method, I think I'll be using it considerably more often now. – acqu13sce Aug 08 '10 at 03:58
0

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.

Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
  • Thanks for the answer, I'm using a number formatter because the numbers might eventually get big enough to overflow an int so I can't presume that intValue will work. – acqu13sce Aug 07 '10 at 11:28
  • Well there is `doubleValue` and `longValue` methods as well. – Alex Wayne Aug 07 '10 at 18:07
0

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).

Michael Kessler
  • 14,245
  • 13
  • 50
  • 64