Storing a floating point array in NSDictionary

I try to save c-float arrayin NSDictionaryfor use later.
At first I used NSArrayto store C-data, but NSArrayshould slow down my intentions.

I use the following code to wrap arrays in an NSDictionary:

[self.m_morphPositions setObject:[NSValue valueWithBytes:&positionBuff objCType:@encode(float[(self.m_countVertices * 3)])] forKey:fourCC];

And fetching a C-Float array using:

float posMorphs[(self.m_countVertices*3)];

NSValue *posValues = [self.m_morphPositions objectForKey:name];

[posValues getValue:&posMorphs];

When I delete the array, the values ​​for each index are 0.0, which is wrong.

How can i fix this?

+5
source share
4 answers

NSValueprobably intended for scalar values, not arrays. In this case, use NSDatashould be much easier.

NSData* data = [NSData dataWithBytes:&positionBuff length:(self.m_countVertices * 3 * sizeof(float))];
[data getBytes:posMorphs length:(self.m_countVertices * 3 * sizeof(float))];

Another solution is to allocate an array on the heap and use NSValueto store the pointer.

+2

, NSData, , . - : @encode , .

@encode(float[(self.m_countVertices * 3)])

. , , NSValue.

. , [<count>^f] (. Type Encodings), :

const char *enc = [[NSString stringWithFormat:@"[%d^f]", (self.m_countVertices * 3)] UTF8String];
NSValue *val = [NSValue valueWithBytes:positionBuff objCType:enc];
+3

NSDictionary, NSData.

, NSMapTable NSPointerFunctionsOpaqueMemory ( MallocMemory) .

+1

I'm not sure if this is how you code your value, but it can help to encapsulate your array into a structure.

// Put this typedef in a header
typedef struct
{
    float values[3];
} PosValues;

In your code:

// store to NSValue
PosValues p1 = { { 1.0, 2.0, 3.0 } };
NSValue *val = [NSValue valueWithBytes:&p1 objCType:@encode(PosValues)];

// retrieve from NSValue
PosValues p2;
[val getValue:&p2];

NSLog(@"%f, %f, %f", p2.values[0], p2.values[1]. p2.values[2]);

The advantage of this approach is that your array is stored as an array type. In addition, these structures can be assigned, although the original arrays are not:

PosValues p1 = { { 1.0, 2.0, 3.0 } };
PosValues p2;

p2 = p1;
0
source

All Articles