简体   繁体   中英

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;

NSArray s 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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM