o9s
is a microblog
home archives search feed blogroll


Primitives To Objects And Back

Usually Objective-C is a very verbose language. To wrap an int primitive in an NSNumber object, you could do -

int i = 10;
NSNumber *numberObject = [NSNumber numberWithInt:i];

- but you can also use the @ shortcut -

int i = 10;
NSNumber *numberObject = @(i);

@ works on any primitive, it always wraps into an NSNumber.

NSNumber *booleanObject = @YES;
NSNumber *floatObject = @(1.5f);
NSNumber *charObject = @('a');

To convert back, all you need to do is this.

BOOL myBool = [booleanObject boolValue];
float myFloat = [floatObject floatValue];
char myChar = [charObject charValue];

This is handy because some APIs and data structures only handle objects. For example, this does not work.

NSMutableArray *array = [NSMutableArray new];
[array addObject:10];

You need to do this instead.

NSMutableArray *array = [NSMutableArray new];
[array addObject:@(10)];

It’s a lot shorter and more readable than this.

NSMutableArray *array = [NSMutableArray new];
[array addObject:[NSNumber numberWithInt:10]];
Posted on 2018-03-28   #objc  






← Next post    ·    Previous post →