Convert string to int-objective c

61,138

Solution 1

To parse string to integer you should do:

NSString *a = @"123abc";
NSInteger b = [a integerValue];

Solution 2

Perhaps fractionally off-topic, but to convert to ASCII you could just use:

[NSString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]

Or in your example:

return [text dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

This will return an NSData which you could iterate through to obtain a string representation of ASCII (s per your method) if this is what you require.

The reason for using this approach is because NSString's can store non-ASCII characters, you will of course potentially lose detail, but enabling the allowLossyConversion flag will attempt to overcome this. As per the Apple documentation:

For example, in converting a character from NSUnicodeStringEncoding to NSASCIIStringEncoding, the character ‘Á’ becomes ‘A’, losing the accent.

Share:
61,138
DonyorM
Author by

DonyorM

I'm a programming hobbyist interested in a variety of languages; I have dabbled in Java, Python, Clojure, and others. On SO I enjoy helping out where I can. Currently working on my project to allow Linux computers to incrementally clone hard drives to any drive, including smaller ones. Check it out at https://github.com/DonyorM/weresync

Updated on July 10, 2022

Comments

  • DonyorM
    DonyorM almost 2 years

    I haven't been able to figure out how to convert a NSString to an int. I'm trying to convert ASCII to text, but to do that I need to convert a string to an int.

    I find it really strange that this isn't anywhere online or in stack overflow. I'm sure I'm not the online one who needs this.

    Thanks in advance for helping.

    P.S. If this helps here is the code I'm using to convert to ASCII:

    + (NSString *) decodeText:(NSString *)text {
        NSArray * asciiCode = [text componentsSeparatedByString:@"|"];
        int i = 0;
        NSMutableString *decoded;
    
        while (i < ([asciiCode count]-1) ) {
    
            NSString *toCode = [asciiCode objectAtIndex:i];
            int codeInt = toCode;
            NSString *decode = [NSString stringWithFormat:@"%c", codeInt];
            [decoded appendString:decode];
    
        }
    
        return decoded;
    }