Is self retained within this Objective-C block?

2019-03-21 13:26发布

问题:

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?

回答1:

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.