views:

60

answers:

2

I have the following C Struct defined :

typedef struct { float x; float y; float z; } metric;

I want to store accelerometer points in an array and do something with it later.

So I have a mutable array that is initialized like so in my viewDidLoad method :

metricsArray_ = [[[NSMutableArray alloc] init]retain];

in my didAccelerate method I create a struct to store the values and add it to the array :

metric metricData;
metricData.x = acceleration.x;
metricData.y = acceleration.y;
metricData.z = acceleration.z;

NSValue *metricObject = [[NSValue valueWithBytes:&metricData objCType:@encode(struct metric)]retain];
[metricsArray_ addObject:metricObject];  

Later when i stop polling for data I try iterate over the array and log the values but the values are all zero :

NSEnumerator * enumerator = [metricsArray_ objectEnumerator];
id element;
while(element = [enumerator nextObject])
{
    metric metricData;
    [element getValue:&metricData];
    NSLog(@"x=%f,y=%f,z=%f",metricData.x, metricData.y,metricData.z);
}

What am I doing wrong here ? And is there a better way to store accelerameter data points? I wanted to store them in a struct rather than an object ( although you end up having to use NSValue anyways )

Thanks

+1  A: 

My initial thought is: why do you need a metrics struct if you just use it for x/y/z values. There already is an object for that: UIAcceleration.

I have a game that stores instances of UIAcceleration in an NSMutableArray about 60 times per second as they are received in the accelerometer:didAccelerate: callback. Zero performance issues.

(I am using the NSMutableArray as a 'ring buffer'. When more than N obejcts have been added, items are removed from the beginning. SO that I just capture the last N seconds)

St3fan
A: 

I couldn't even compile your code above. I had to make the following change of removing the struct in the @encode(). This then seemed to compile and work.

NSValue *metricObject = [NSValue valueWithBytes:&metricData objCType:@encode(metric)];

There also appears to be an unnecessary retain.

No one in particular