weakRefrence 到Invocation(一)

   最近在工做中遇到问题,就是个人代理层有两个方法 一个是添加代理 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。

相关文章
相关标签/搜索