josef
josef

Reputation: 1632

addObject to an NSMutableArray is not working

I wrote a code :

    int SIZE= 516;
NSMutableArray  *sensorData, *sensorDataX,....,= [NSMutableArray arrayWithCapacity:SIZE];
NSString *strSensorData = [NSString stringWithFormat:@"%.6f %.6f %.6f %.6f ", deviceMotion.timestamp, deviceMotion.userAcceleration.x, deviceMotion.userAcceleration.y, deviceMotion.userAcceleration.z];
NSString *strSensorDataX = [NSString stringWithFormat:@"%.6f %.6f ", deviceMotion.timestamp, deviceMotion.userAcceleration.x];
[sensorData addObject:strSensorData];
[sensorDataX addObject:strSensorDataX];

And when I am checking it with:

NSLog(@"Data : %@ ", sensorDataX   ); 

I am getting just (null). Even so by:

NSLog(@"Data : %@ ",strSensorDataX)

Its giving the right array. Do somebody Know why?

Thanks

Upvotes: 0

Views: 155

Answers (3)

Aditya Sinha
Aditya Sinha

Reputation: 103

You should definitely take a look here on how to Initialize and allocate multiple variables/objects.

This would look more elegant.

NSMutableArray *sensorData = [NSMutableArray arrayWithCapacity:SIZE]; 
NSMutableArray *sensorDataX = [sensorData mutableCopy]; 
NSMutableArray *sensorDataY = [sensorData mutableCopy];
// and so on..

Hope this helps.

Upvotes: -1

rmaddy
rmaddy

Reputation: 318944

This line:

NSMutableArray  *sensorData, *sensorDataX,....,= [NSMutableArray arrayWithCapacity:SIZE];

will only assign the last variable to the new array. Split it into separate lines for each variable.

NSMutableArray *sensorData = [NSMutableArray arrayWithCapacity:SIZE];
NSMutableArray * sensorDataX = [NSMutableArray arrayWithCapacity:SIZE];
// and the rest

Upvotes: 2

Dima
Dima

Reputation: 23634

I just tried it myself and it appears that you can't initialize multiple objects in one statement the way you're trying to do. Only one of the objects in the group seem to actually get initialized (the last one, in my tests), while the others remain nil. Split up your array initialization into separate statements and it should work fine.

NSMutableArray *sensorData = [NSMutableArray arrayWithCapacity:SIZE];
NSMutableArray *sensorDataX = [NSMutableArray arrayWithCapacity:SIZE];

Upvotes: 3

Related Questions