Search code examples
objective-ciosclassaccelerometer

CMAccelerometerData class Vs. deprecated UIAccelerometer class


Based on this documentation, the CMAccelerometerData class (found in the Core Motion framework) has a property of type CMAcceleration called acceleration that is a typedef of a struct containing 3 values (double x, double y, double z)

I'm rather new to Objective-C (I only know C++..) so my question is this : How do I access, let's say the double y value kept in that property, at some point during my code?

Do I first create an instance of the CMAccelerometerData class like this :

CMAccelerometerData *myAccelerometer;

then access its acceleration property :

double axisYvalue = [myAccelerometer acceleration]; 

the above is obviously wrong, isn't it? I have to get the Y found in acceleration specifically so how do I do that?

double axisYvalue = [myAccelerometer acceleration->y]; // no this is wrong as well..

so how do I do it?

And one last question if I may :)

given this specific class and property that I mentioned.. and let's say I've instantiated my CMAccelerometer class.. Now every time, during my code, I use something like

return [myAccelerometer acceleration->y]; // let's say that's the correct version :)

inside some -(double) method .. will I be getting the value of the Y-axis at that specific moment in which the call is being made ?

I am asking this because I got confused when reading about the now deprecated UIAccelerometer class where you had to define intervals and update the values of x,y,z every so often etc.. where as now I can get the value that is being exercised on the Y-axis the moment the call to the acceleration property is made, isn't that the case?

phew... sorry for the length of this text! :)


Solution

  • Coming from C++, I assume it's safe to assume that you understand pointers. That first line:

    CMAccelerometerData *myAccelerometer;
    

    ...isn't creating an instance, it's declaring a pointer to an instance, which won't point to anything valid. To get a valid instance, you'll never actually create one of these yourself. Instead, you'll use the CMMotionManager class' accelerometerData property to get a pointer to a valid object:

    // Sometime earlier...
    CMMotionManager* manager = [[CMMotionManager alloc] init];
    [manager startAccelerometerUpdates];
    
    // Sometime in the present...
    // Get a ref to the most recent accelerometer data.
    CMAccelerometerData* data = [manager accelerometerData];
    
    // Access it.
    double x = [data acceleration].x;