Domanda

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?

È stato utile?

Soluzione

- (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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top