Dinesh
Dinesh

Reputation: 939

Storing a double array as NSNumber

I have a variable double * data = malloc(sizeof(double)) in objectiveC;

I am using this variable as an double array like data[] to store some data. Now I want to add this data variable (which is an double* array) as an object NSNumber in iOS. Any idea how I can turn it into iOS object likeNSNumber`?

Upvotes: 1

Views: 656

Answers (3)

rptwsthi
rptwsthi

Reputation: 10172

Based on Mundi's answer, try this:

NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:0];
for (int i = 0; i < lengthOfDoublearray; i++) { // as premitive DataType array needs predefined length
    [array  addObject:[NSNumber numberWithDouble:data[i]]];
}

Here data is array of double (that you used).

Upvotes: 1

Martin R
Martin R

Reputation: 539815

You can use NSData to wrap an arbitrary byte buffer into an Objective-C object.

Use dataWithBytes:length: to create an NSData object from your double array, and bytes: or getBytes:length: to retrieve the data bytes back from the NSData object.

Upvotes: 2

Mundi
Mundi

Reputation: 80273

You cannot turn an array of primitives into one NSNumber. This does not make any sense.

You can, however, turn an array of doubles into an array of NSNumbers. Iterate through your double* array and add each number to an NSMutableArray as NSNumber using its class method numberWithDouble:.

Upvotes: 1

Related Questions