Search code examples
iosobjective-cnsnotificationcenter

Objective-C - UIViewController loading on top of another controller


I'm using the NSNotification centre to detect changes of currency so I can update all the other classes. When a currency change occurs, all the other classes and views get updated, however when there is no currency change, and if you press the back button to go back to the home page the view loads on top of the already existing view.

Code for NSNotification center

  if ([overviewModel.currency isEqual:@"GBP"]){
                [[NSNotificationCenter defaultCenter] postNotificationName:@"DataUpdated"
                                                                    object:self];
            } else {

                [[NSNotificationCenter defaultCenter] postNotificationName:@"DataUpdated"
                                                                    object:self];
            }

Code for handling updated data in homepage:

  for (UIView *b in self.view.subviews) {
    [b removeFromSuperview];
}


self.build = [[ApiRequestBuild alloc]initWithVersionKey:kAPI_VERSION_KEY requestType:kAPI_REQUEST_TYPE data:@""];
[self.build setQueryWithSection:@"homepage" value:@"" parameter:@[]];

self.request = [[ApiRequest alloc]init];
self.request.delegate = self;
[self.request sendRequestWithParams:[self.build buildConfig] toUrl:kAPI_URL_STRING];

I know why this is happening, the request gets sent again so the page loads on top of the already existing page, what I don't understand is why doesn't the remove from subview code get rid of the of the view and how would I be able to fix this? thanks


Solution

  • The removeFromSuperview won't work if it's being called from another thread (than main thread). Your notification will be received on the same thread it was fired from. I'll wager that you're listening to a model change event (regarding your currency state) on another thread.

    Try dispatching to main queue before walking your copy of subviews to remove them all.