Domanda

I'm working on doing network requests in my app and am using NSBlockOperations in an NSOperationQueue to do this asynchronously. However, I want to be able to cancel these operations if the view controller that called them is deallocated (has been popped off the navigation stack).

This is a simplified version of what I have:

NSArray *posts;

__weak DataController *weakSelf = self;
NSBlockOperation *fetchPostsOperation = [NSBlockOperation blockOperationWithBlock:^{
    DataController *strongSelf = weakSelf;
    NSDictionary *response = [weakSelf refreshPostsInPart:PartFirst];
    posts = [response objectForKey:@"posts"];
}];

[self.queue addOperation:fetchPostsOperation];

In the refreshPostsInPart: method of DataController I make repeated network requests for paginated data from App.net using a while loop. At each iteration of the loop I check a property of DataController self.isCancelled (of type BOOL), if it is NO I keep making requests.

In my dealloc method of DataController I set this property to be YES so that on the next iteration of the while loop I will stop making requests. In essence, I'm implementing a poor mans cancelAllOperations while using NSBlockOperation.

Question: When setting self.isCancelled to NO in my dealloc method, am I also setting self.isCancelled for the strongSelf reference that is being used in the block?

È stato utile?

Soluzione

self, weakSelf, and strongSelf all refer to the same object in memory. That means that if you send a message to self in dealloc (which you do by setting that property), weakSelf and strongSelf also "know" about this updated property. So, yes, you are setting self.isCancelled (more than likely the actual property's name is self.cancelled and its getter is isCancelled) on strongSelf as well.

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