views:

3359

answers:

4

I'm new to Objective-C and iPhone development, and I'm trying to store floating-point values in an NSMutableArray, but when I do I get an error saying "incompatible type for argument 1 of 'addObject". What am I doing wrong? I'm trying to create an array of doubles that I can perform math calculations with.

+7  A: 

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

[myDictionary setObject:[NSNumber numberWithFloat: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.

sjmulder
+12  A: 

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.

Ryan Townshend
Use numberWithFloat if you don't need the precision.
Georg
+3  A: 

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:

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

// ...

[prices addObject:price];
Jason Coco
A: 

a lot of people may not notice answer #3, but it basically solved both of the problems i was having with trying to store a float into an array. I actually couldn't dot it with the #1 answer. i just wanted to post a a big thank you because this has had me up for 2 nights and 2 days!

WiZ