Question

I would like to implement a self-retained network lib that can be used also with ARC.

The calling code for this lib should be like the following.

- (void)downloadData {

    NSURL *url = // alloc-init
    NetworkFetcher *networkFetcher = [[NetworkFetcher alloc] initWithURL:url];
    [networkFetcher startWithCompletionHandler:^(NSData *data){
        _fetchedData = data;
    }];
    // under ARC it will put a release call for the networkFetcher here
}

This approach is used by TWRequest (if I am not wrong it's deprecated now) class in Twitter framework. The advantage is that the caller does not need to maintain the fetcher alive itself.

Some details. The startWithCompletionHandler copies the block for future reuse. When the request has finished, the fetcheher releases the block settima it to nil.

So, what the approach I need to follow so the fetcher can be self-retained? Any best pratice?

Was it helpful?

Solution

You can add a "private" property

@interface NetworkFetcher ()
@property (strong, nonatomic) NetworkFetcher *selfRef;
@end

in a class extension to the NetworkFetcher class. In startWithCompletionHandler, you set

self.selfRef = self;

to prevent the object from being deallocated. When the request has finished and the completion block has been called, set

self.selfRef = nil;

to destroy the retain cycle.

OTHER TIPS

I usually use the technique described by Martin R which basically imitates the older retain and release but there are also other methods.

You can capture the fetcher in the completionHandler. Just use self anywhere in the completion handler and don't forget to release the block when it has been called. This is a bit less readable then using a property but it follows the same principle

Another method is to have a singleton (mutable) array of active fetchers. Adding/Removing follows the same principle as with self.selfRef property.

With a singleton array there is one big advantage - you can access the fetchers whenever you want - cancel them or just get the number of active fetchers (to limit number of simultaneous downloads, for example).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top