Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to int-objective c [duplicate]

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;
}
like image 275
DonyorM Avatar asked Aug 29 '13 07:08

DonyorM


2 Answers

To parse string to integer you should do:

NSString *a = @"123abc";
NSInteger b = [a integerValue];
like image 93
User 1531343 Avatar answered Nov 08 '22 05:11

User 1531343


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.

like image 23
John Parker Avatar answered Nov 08 '22 05:11

John Parker