0

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?

2 Answers 2

1

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)];
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.