Is self retained within this Objective-C block?

送分小仙女□ 提交于 2019-12-04 12:35:30

问题


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.



来源:https://stackoverflow.com/questions/6433790/is-self-retained-within-this-objective-c-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!