Kevin Science Kevin Science - 5 months ago 14
Objective-C Question

How to stop functions recursion by objective c in iOS

EDIT: I admit my design has problem. I will move my timer to a none-UI-related-function.

First, I have multiple accounts. I have a collectionView to load one account's information.

Second, I have two functions. One is my collectionView's cellForItemAtIndexPath function. I have a timer in it to call another function to renew the logged account's data.

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

//updateUI methods..

if (// a rare situation ){
dispatch_async(dispatch_get_main_queue(), ^{
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:3.0
target:self
selector:@selector(refreshSingleVMStatusForTimer:)
userInfo:nil repeats:NO];
});
}
}


and here is refreshSingleVMStatusForTimer function to download all the data from internet then call
[collectionView reloadData]
to update it.

- (void) refreshSingleVMStatusForTimer :(NSTimer *) timer {

//download the data from internet
//parse the xml to useful data.

[collectionView reloadData];
}


So these two functions becomes a recursion.

Now If I switch account, my collectionView will load a different account's data in it. But the recursion is still running which will occur error.

I don't know whether I explain my problem clear or not. If you have any question, please tell me.

Answer

As mentioned by Avi it is a design problem, that doesn't let you stop the recursion: You should not trigger a reload in -cellForItem:atIndexPath:. This is making the bock for gardeners. Remove it.

If there is a reason to do it there, isolate that and ask a new Q.