最近在工做中遇到問題,就是個人代理層有兩個方法 一個是添加代理 addDelegate:(id)delegate onQueue:(dispatch_queue_t)queue; 一個是刪除代理 removeDelegate:(id)delegate;我都是添加到數組中。若是隻是普通的添加會致使實現實例沒法釋放。數組
因而就想方法把添加的實例的弱引用添加到數組。開始我是這樣弄:atom
WeakRefrenceObject makeWeakRefrenceObject(id object){
__weak typeof(object)weakObject = object; return ^id{ return weakObject; }; }
須要獲取到對象就這樣弄:spa
id getObjectOnWeakReferenceObject(WeakReferenceObject ref){
if (ref == NULL) return nil; else return ref(); }
使用弱指針將對象地址保存到Block中,而後添加到數組。線程
由於還須要根據每一個線程發送消息。因此咱們進一步進化:代理
@interface LIPDelegateNode :NSObject指針
{code
#if __has_feature(objc_arc_weak)對象
__weak id delegate;blog
#if !TARGET_OS_IPHONErem
__unsafe_unretained id unsafeDelegate;
#endif
#else
__unsafe_unretained id delegate;
#endif
dispatch_queue_t delegateQueue;
}
#if __has_feature(objc_arc_weak)
@property (atomic,readwrite,weak) id delegate;
#if !TARGET_OS_IPHONE
@property (atomic,readwrite,unsafe_unretained) id unsafeDelegate;
#endif
#else
@property (atomic,readwrite,unsafe_unretained) id delegate;
#endif
@property (nonatomic,readonly) dispatch_queue_t delegateQueue;
- (instancetype)initWithDelegate:(id)delegate onQueue:(dispatch_queue_t)delegateQueue;
@end
咱們將對象和對象執行線程封裝成一個類型,而後經過類去管理。這裏須要注意的是區分arc 和mrc,還有就是對象是否支持weak,(example. NSViewController等不支持)咱們就是用unsafe_unretained。