Random programming things I'd want to remember

Sunday, February 26, 2012

Objective-C: String to number to object conversion notes

So you need to add a double into an NSMutableArray, but you cannot do it directly because double is not an object. Here is how you wrap a double into an object type of NSNumber and add it to the array:
//create and initialize array:
NSMutableArray *arr = [NSMutableArray array];

//add your double to the array:
[arr addObject:[NSNumber numberWithDouble:yourNumber]];

//Here is how you unwrap it back into a double:
NSNumber *someNumber = [arr lastObject];

double d = [someNumber doubleValue];

Here is another handy trick, it turns out that NSString has a method that tries to return a double from the string itself. Here is how you write it:
NSString *myString = @"5.0";
double result = [myString doubleValue]; //I bet there is also a method to return an integer in the same manner

Here is how a double is converted to an NSString object:
NSString *resultString = [NSString stringWithFormat:@"%g", result];

No comments: