Reputation: 3567
I want to add an NSObject to an NSMutableArray inside of a a block. In the code below, the NSLog line works fine and returns the number I expect. However, when I try to add that result to an NSArray, the array is always empty when I go to access it later.
CMStepQueryHandler stepQueryHandler = ^(NSInteger numberOfSteps,
NSError *error) {
NSLog(@"CMStepQueryHandler: Steps on day: %i", (int)numberOfSteps);
[stepsPerDay addObject:[NSNumber numberWithInt:numberOfSteps]];
};
How can I add an object to an NSMutableArray (in this case stepsPerDay) from inside of a block so that I can access it later?
Upvotes: 0
Views: 151
Reputation: 3567
The problem was that the block would always execute the addObject after I had tried to work with the contents of the array, I guess due to the fact that the block was executed asynchronously. The solution was to have the block call a function which worked with the array and that way I could guarantee the object would deb added to the array when the function was executed.
Upvotes: 0
Reputation: 108131
The code looks fine.
I suspect you forgot to initialize stepsPerDay
. It should be
NSMutableArray *stepsPerDay = [NSMutableArray array];
As a non-related advice, you may also consider a more modern syntax
[stepsPerDay addObject:@(numberOfSteps)];
Upvotes: 1