Site icon ChrisWrites.com

How to Convert Between Datatypes Types in Xcode

Datatypes in objective-c are easy to change between. But often you find yourself looking all over the web, on forums for the answers.

Converting between types is a big problem if done wrong. If you convert the variable wrong your app will crash. The app may not crash until another point in your app. Such as when another function trys to read the variable. This guide should help minimise these problems and save you time.

This guide also features how to print each variable to the console. If you put the wrong type in the NSLog, the app will just print null or crash.

NSInteger

To NSNumber
[NSNumber numberWithInteger:integer];

To NSString
[NSString stringWithFormat:@"%d", integer];

NSString

To NSInteger
[string intValue];

To NSNumber
[NSNumber numberWithInt:[string intValue]];

NSNumber

To NSString
[NSString stringWithFormat:@"%@", number];

To NSInteger
[number integerValue];

NSData

To NSString
[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];

To NSSInteger
[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
[string intValue];

To NSNumber
[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
[NSNumber numberWithInt:[string intValue]];

NSLog console commands to print types

Display NSString
NSLog(@"%@", string);

Display NSInteger
NSLog(@"%d", int);

Display NSFloat
NSLog(@"%f", float);

If you have any other requests for types which aren’t here please comment.

Exit mobile version