问题
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