Below code snippet is in objective C
__weak MyView *weakSelf = self;
dispatch_async(dispatch_get_main_queue(), ^{
[weakSelf.activityIndicatorView stopAnimating];
[weakSelf.activityIndicatorView removeFromSuperview];
weakSelf.activityIndicatorView = nil;
});
- Will the
weakSelfalways available/valid since it is inside the main queue? - Do we need to declare
strongSelfonly when block is other than the main queue?
Your code snippet is too small to answer on your questions fully.
weakSelfcan be bothnilor non-nil. The keywordweakmeans that variableweakSelfcan becomenilin some cases. For example, if your controller has the following property:In some cases you dismiss this controller and after that you call the method
fformyView:Code of the method
fis based on code snipped you provided in this question:I guess you will see in debugger that the
weakSelfwill benilwhen you will try to callstopAnimatingforactivityIndicatorView. And I guess you can easily reproduce the situation whenweakSelfwill be not cleared. It means that the answer on your first question is "No, theweakSelfwill be not always available/valid and the main thread does not protect you fromnilin this variable"You need to use
strongSelf(__stronginstead of__weak) if you don't want to loose a reference to variable inside block. For example, if in the classMyViewthere is a methodlogthat logs some debug information:And if you want to log information always after the code in your code snippet will called use the following version of the method
f:So, the answer, on your second question is "No, you need to use
__strongbased on your application, the block can be completed in different threads".