Question

I want to read many different integer values out of an textfield and for that I have this code:

NSString *string1,*string2;
string1= [textField stringValue];
int i,c;
c=0;
NSInteger values[50];
for (i=0; i<50; ) {
    string2=[NSString stringWithFormat:@"%@%i%s",@" ",i,","];

    NSRange range=[string1 rangeOfString:string2];

    if (range.location != NSNotFound) {
        values[c]=i;
        c=c+1;

    }
    i=i+1;
}

there is no problem with that but it can't read the first number in string like that "2, 3, 15" but I want it that it can also read a string like that, so could anybody please help me with this problem.

And if I make string2 like this @"i", "," it causes problems with values like 15 because it reads 5 and 15

Was it helpful?

Solution

How about doing this instead:

NSArray *integerStrings = [[textField stringValue] componentsSeparatedByString:@","];

for (NSString *integerString in integerStrings) {
    NSDecimalNumber *number = [NSDecimalNumber decimalNumberWithString:integerString];

    // do whatever you want with the number...
}

Alternatively, if the numbers are always integers, the loop could be:

for (NSString *integerString in integerStrings) {
    NSInteger number = [integerString integerValue];

    // do whatever you want with the number...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top