1

I am working on an iOS app that uses navigation controllers. In several of the view controllers I create an instance of a class, Request. In this class I have a method that has a block:

- (void)submitRequest:(NSMutableDictionary *)dictionary
{
    [[API sharedInstance] commandWithParams:dictionary
                               onCompletion:^(NSDictionary *json) {
                                   if (!_canceled) {
                                       [self.delegate receivedRequest:json];
                                   }
                               }];
}

The problem I have is that if the request has been received when UIViewControllers due to navigation have changed, then the app will crash. So I want to set canceled to YES when the navigation controller changes view controllers.

How can I cancel the request when the navigation changes?

jww
  • 97,681
  • 90
  • 411
  • 885
user906357
  • 4,575
  • 7
  • 28
  • 38

1 Answers1

3
- (void)submitRequest:(NSMutableDictionary *)dictionary
{
    __weak MyClass *weakSelf = self;
    [[API sharedInstance] commandWithParams:dictionary
                               onCompletion:^(NSDictionary *json) {
                                   if (!_canceled) {
                                       [weakSelf.delegate receivedRequest:json];
                                   }
                               }];
}

Your Block captures self, so you may get a retain cycle. Use a weak reference to avoid that.

jscs
  • 63,694
  • 13
  • 151
  • 195
johnMa
  • 3,291
  • 24
  • 37
  • It answers my question better than I had asked. I was using the canceled bool to prevent the crash, this fixes the crash without need for canceled.Thank you – user906357 Jan 12 '14 at 17:33