Is accessing instance variables by reference safe?

我只是一个虾纸丫 提交于 2019-12-24 13:35:05

问题


What is the difference between the two code snippets below:

1.

__block __weak NSMutableArray *arrBlock = self.arr ;
[[AsyncRequest initRequest:url onCompletedBlock:^(NSMutableArray *arr) {
         arrBlock = arr;
    }]ExecuteRequest];

2.

id __weak weakself  = self;
[[AsyncRequest initRequest:url onCompletedBlock:^(NSMutableArray *arr) {
         weakself.arr = arr;
    }]ExecuteRequest];

Neither of them cause retain cycles, but Apple suggests using the first one. Is there a problem with the second one?


回答1:


They have different effects. The first updates the local variable and the second updates the instance variable (property).

Which one you want to use depends on what you want to happen, however I suspect you want the second as the first looks like a no-op if that block is executed asynchronously.



来源:https://stackoverflow.com/questions/25548651/is-accessing-instance-variables-by-reference-safe

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