开发者

Convert NSString to Integer in objective - c

I have an array that stores each digit of a phone number as a string. I then pass the phone number digit string as an argument for objectAtIndex: method of NSArray like this: [myArray objectAtIndex: [myString intValue]]; The compiler says I need to cast the String but开发者_StackOverflow中文版 I am already doing that. What is wrong?

Update:

Here's my actual line of code:

NSMutableArray *tmp = [[NSMutableArray alloc] initWithArray:[charHolder objectAtIndex:[[phoneNumDigits objectAtIndex:i]intValue]]];

This is where the error is, phoneNumDigits is an array of each digit of the phone number, charHolder is the array holding the array of letters associated with each digit.


Your question is a little confusing to me. Here is how I understand what you want to do:

You have an NSArray named phoneNumDigits. This array contains a few NSString objects. Each string is something like @"1" or @"4" and represents a single digit of a phone number.

Now you want to convert each of those digit strings to int or NSInteger and want to store these integers in another array.

If I understood you correctly, here is my answer:

You cannot exactly do what you want, because you can't put a simple data type like an int or a float into an NSArray.

That's why there is the wrapper class NSNumber. You can package a simple int in an NSNumber and store this NSNumber in an NSArray.

So to get your string digits from the phoneNumDigits into the tmp array you could use this code:

for (NSString *digitAsString in phoneNumDigits)
{
    NSNumber *digitAsNumber = [NSNumber numberWithInt:[digitAsString intValue]];
    [tmp addObject:digitAsNumber];
}

To get the ints out of the tmp-NSArray you would use

int digit = [[tmp objectAtIndex:idx] intValue];

I hope this helps, but I'm not sure I understand what you want to do here. I could be completely missing the point. Maybe you could share some more code.


NSMutableArray *tmp = [[NSMutableArray alloc] initWithArray:[charHolder objectAtIndex:[[phoneNumDigits objectAtIndex:i]intValue]]]; 

objectAtIndex returns a generic object (id). It has no idea that the object in the array is a string as it could be anything. So you need to cast it. Or to increase readabilty, create variables for them. Eg:

int phoneNumberDigit = [phoneNumDigits objectAtIndex:i];
NSArray *chars = [charHolder objectAtIndex:phoneNumberDigit];
NSMutableArray *tmp = [[NSMutableArray alloc] initWithArray:chars];
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜