Jon
Jon

Reputation: 397

How to create an NSMutableArray of floating point values

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.

Upvotes: 30

Views: 38015

Answers (4)

Sijmen Mulder
Sijmen Mulder

Reputation: 5819

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.

Upvotes: 11

Sanjay Kakadiya
Sanjay Kakadiya

Reputation: 107

NSMutableArray *muArray = [[NSMutableArray alloc] init];
NSNumber *float = [NSNumber numberWithFloat:210.0f];
NSNumber *float1 = [NSNumber numberWithFloat:211.0f];
[muArray addObject:float];
[muArray addObject:float1];

NSlog(@"my array is--%@",muArray);

Upvotes: 1

Ryan Townshend
Ryan Townshend

Reputation: 2394

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.

Upvotes: 63

Jason Coco
Jason Coco

Reputation: 78353

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];

Upvotes: 7

Related Questions