I'm using Parse as my backend. Saving/fetching objects runs in a separate thread from the main thread, so if you are doing anything with the data you are trying to fetch, you must do it in a background block, like this:
[Card fetchInBackgroundWithBlock:^(PFObject *object, NSError *error) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
...
//setting up button based on Card's name
...
[buttonArray addObject:button];
}];
This creates a new thread, and when the object has been fetched from Parse, the code inside the block runs.
I'm adding a button for each Card object from an array of cards attached to the parse user. When you press the card button, you can see some info about it, and also choose to delete it. I perform an unwind segue which handles removing the button for the deleted card as well as shifting any buttons beneath the deleted one up, so there aren't gaps. My problem is that since the buttons are created and added to my array inside of the other thread, some objects manage to be fetched out of order. So my screen may show buttons in the order 1 2 3 4, but my array holds buttons [3,2,1,4]. How can I make sure I am keeping the buttons in the array in the same order that they appear on screen, which is the same order the cards are stored in my Parse array?
Here's how I'm deleting buttons currently, which is moving incorrect buttons:
-(IBAction)prepareForUnwindPaymentCardDeleted:(UIStoryboardSegue *)segue
{
[buttonArray removeObjectAtIndex:cardNum];
for( int i = cardNum; i < [buttonArray count]; i++)
{
UIButton *button = [buttonArray objectAtIndex:i];
[button setTag:i];
[button setFrame:CGRectMake(xCenter-width/2, button.frame.origin.y - 52, width, height )];
}
yValue -= 52;
}
yValue is the y coordinate of the button's origin, and corresponds to the y coordinate that the next button should be placed at if I add a new card/button. Hence, when I remove a button/card, I decrement yValue so I don't leave a gap between my current last button and a new button. cardNum is a variable that is equal to the index of the card in my Parse array, and is also the index of the button in the order that it appears. However, I've found that it isn't always the index of the button inside of buttonArray.
What I want is for my NSMutableArray buttonArray to have its indices correspond to the order the buttons appear on the screen, so if I delete button 3, I have to shift buttons 4-n up to fill in the gap, then decrement each of their tags to correspond to the correct card.
edit - My solution ended up being to just create the button and add it to my array before the fetchinbackground call. That way, everything was being added in the order I expected. I improperly used the insertObjectAtIndex method, but since I was adding to the index equal to count, it didn't throw any errors. When I learn a little more about them, I'll be using an NSMutableDictionary instead, as suggested by Josh and Duncan.