Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is self retained within this Objective-C block?

When I have a block in Objective-C that looks like this:

self.request = [[ASIHTTPRequest requestWithURL:...

[self.longPollRequest setCompletionBlock:^{
    NSLog(@"%@", self.request.responseString);
}];

will it retain self or explicitly retain self.request?

like image 279
Chris Avatar asked Jun 22 '11 01:06

Chris


1 Answers

As the Block Programming Topics says:

In a reference-counted environment, by default when you reference an Objective-C object within a block, it is retained. This is true even if you simply reference an instance variable of the object. Object variables marked with the __block storage type modifier, however, are not retained.

If you use a block within the implementation of a method, the rules for memory management of object instance variables are more subtle:

If you access an instance variable by reference, self is retained;

If you access an instance variable by value, the variable is retained.

you reference self in block, so self is retained.

like image 80
cxa Avatar answered Oct 18 '22 03:10

cxa