Convert NSString to Integer in object - c

I have an array that stores each digit of a phone number as a string. Then I pass the digital string of the phone number as an argument to objectAtIndex : method of NSArray as follows: [myArray objectAtIndex: [myString intValue]]; The compiler says I need to use String, but I'm already doing it. What's wrong?

Update:

Here is my actual line of code:

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

Here's the error, phoneNumDigits is an array of each digit of the phone number, charHolder is an array containing an array of letters associated with each digit.

+4
source share
2 answers

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

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

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

If I understand you correctly, here is my answer:

You cannot exactly do what you want, because you cannot put a simple data type, such as int or float in an NSArray .

This is why there is an NSNumber wrapper NSNumber . You can pack a simple int in NSNumber and store that NSNumber in NSArray .

So, to get the string digits from phoneNumDigits to the tmp array, you can use this code:

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

To get int from tmp- NSArray you have to use

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

Hope this helps, but I'm not sure I understand what you want to do here. I could completely skip this. Perhaps you could share some more codes.

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

objectAtIndex returns a shared object ( id ). He does not know that the object in the array is a string, as it could be anything. So you need to drop it. To increase readability, create variables for them. For instance:

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

Source: https://habr.com/ru/post/1337182/


All Articles