Delegate/Block/NSNotification是最常用的事件同步方法晦炊,各自特點(diǎn)即碗、區(qū)別男应、使用方法就不贅述了。
下面主要想強(qiáng)調(diào)一下再多線程中使用Delegate/Block/NSNotification的注意事項(xiàng)嗤朴。
開發(fā)時Delegate的調(diào)用方法配椭、Block的調(diào)用方法、NSNotification的post方法都可能會在非主線程中調(diào)用播赁,此時Delegate/Block/NSNotification的回調(diào)方法也將被這個非主線程調(diào)用颂郎,尤其是Delegate的實(shí)現(xiàn)方法很少有人會考慮內(nèi)部的多線程實(shí)現(xiàn),比如更新UI容为。由于Delegate/Block/NSNotification可能同時在主線程和非主線程中使用乓序,所以實(shí)現(xiàn)時必須同時考慮兩種情況。例如更新UI的部分需要寫成下面的樣子:
dispatch_async(dispatch_get_main_queue(),^{
UIButton*button = [[UIButtonalloc]initWithFrame:CGRectMake(50,50,100,44)];
[self.viewaddSubview:button];
[buttonrelease];
});
如果很不幸寫成了
dispatch_sync(dispatch_get_main_queue(),^{
UIButton*button = [[UIButtonalloc]initWithFrame:CGRectMake(50,50,100,44)];
[self.viewaddSubview:button];
[buttonrelease];
});
那么在主線程調(diào)用的時候就完了坎背。替劈。。沒有然后了得滤。陨献。。
如果是大型項(xiàng)目你真心不知道別人會干嘛懂更。眨业。急膀。
如果是小型項(xiàng)目你怎么知道以后不會發(fā)展成大項(xiàng)目。龄捡。卓嫂。
所以還是注意點(diǎn)吧!