Yusuf OZKAN
Yusuf OZKAN

Reputation: 115

How can I create an NSArray with float values

I want to make a float value array. How can I do this? My code is:

NSArray *tmpValue = [[NSArray alloc] init];
total = total + ([[self.closeData objectAtIndex:i]floatValue] - total)* expCarpan;
firstValue = total;

Upvotes: 3

Views: 3640

Answers (3)

Stuart
Stuart

Reputation: 37053

NSArrays only take object types. You can add various non-object types to an NSArray by using the NSNumber wrapper:

NSNumber *floatNumber = [NSNumber numberWithFloat:myFloat];
[myArray addObject:floatNumber]; // Assuming `myArray` is mutable.

And then to retrieve that float from the array:

NSNumber *floatNumber = [myArray objectAtIndex:i];
float myFloat = [floatNumber floatValue];

(As you have done in your code above).


Update:

You can also use the NSValue wrapper in the same way as NSNumber for other non-object types, including CGPoint/Size/Rect/AffineTransform, UIOffset/EdgeInsets and various AV Foundation types. Or you could use it to store pointers or arbitrary bytes of data.

Upvotes: 9

Alex Nichol
Alex Nichol

Reputation: 7510

The NSArray class can only contain instances of other Objective-C objects. Fortunately, Apple already has several Objective-C object types for encapsulating C primitive types. For instance, NSNumber can incapsulate many different types of C numbers (integers, floats, etc.). NSValue can incapsulate arbitrary structures, CGPoints, pointers, etc. So, you can use NSNumber and float in conjunction with NSArray as follows:

NSArray * myArray;
NSNumber * myFloatObj = [NSNumber numberWithFloat:3.14];
myArray = [NSArray arrayWithObjects:myFloatObj, nil];

You can then get the original float value from the first NSNumber of the array:

NSNumber * theNumber = [myArray objectAtIndex:0];
float theFloat = [theNumber floatValue];

Alternatively, you can turn this into a one-liner:

float theFloat = [[myArray objectAtIndex:0] floatValue];

Upvotes: 4

sidyll
sidyll

Reputation: 59287

Primitive types can't be included in a NSArray, which is only for objects. For numbers, use NSNumber to wrap your floats.

NSNumber *n1 = [NSNumber numberWithFloat:1.2f];
NSNumber *n2 = [NSNumber numberWithFloat:1.4f];

NSArray *array = [NSArray arrayWithObjects:n1, n2, nil];

Upvotes: 3

Related Questions