How to create an NSMutableArray of floating point values How to create an NSMutableArray of floating point values arrays arrays

How to create an NSMutableArray of floating point values


NSMutableArray only holds objects, so you want an array to be loaded with NSNumber objects.Create each NSNumber to hold your double then add it to your array. Perhaps something like this.

NSMutableArray *array = [[NSMutableArray alloc] init];NSNumber *num = [NSNumber numberWithFloat:10.0f];[array addObject:num];

Repeat as needed.


Use an NSNumber to wrap your float, because the dictionary needs an object:

[myDictionary setObject:[NSNumber numberWithFloat:0.2f] forKey:@"theFloat"];/* or */[myDictionary setObject:@0.2f forKey:@"theFloat"];

retrieve it by sending floatValue:

float theFloat = [[myDictionary objectForKey:@"theFloat"] floatValue];

Code is untested.

You can wrap many other data types in NSNumber too, check the documentation. There's also NSValue for some structures like NSPoint and NSRect.


In Cocoa, the NSMutableDictionary (and all the collections, really) require objects as values, so you can't simply pass any other data type. As both sjmulder and Ryan suggested, you can wrap your scalar values in instances of NSNumber (for number) and NSValue for other objects.

If you're representing a decimal number, for something like a price, I would suggest also looking at and using NSDecimalNumber. You can then avoid floating point inaccuracy issues, and you can generally use and store the "value" as an NSDecimalNumber instead of representing it with a primitive in code.

For example:

// somewhereNSDecimalNumber* price = [[NSDecimalNumber decimalNumberWithString:@"3.50"] retain];NSMutableArray*  prices= [[NSMutableArray array] retain];// ...[prices addObject:price];