weakRefrence 到Invocation(一)
最近在工作中遇到问题,就是我的代理层有两个方法 一个是添加代理 addDelegate:(id)delegate onQueue:(dispatch_queue_t)queue; 一个是删除代理 removeDelegate:(id)delegate;我都是添加到数组中。如果只是普通的添加会导致实现实例无法释放。
于是就想方法把添加的实例的弱引用添加到数组。开始我是这样弄:
WeakRefrenceObject makeWeakRefrenceObject(id object){
__weak typeof(object)weakObject = object;
return ^id{
return weakObject;
};
}
需要获取到对象就这样弄:
id getObjectOnWeakReferenceObject(WeakReferenceObject ref){
if (ref == NULL) return nil;
else
return ref();
}
使用弱指针将对象地址保存到Block中,然后添加到数组。
因为还需要根据每个线程发送消息。所以我们进一步进化:
@interface LIPDelegateNode :NSObject
{
#if __has_feature(objc_arc_weak)
__weak id delegate;
#if !TARGET_OS_IPHONE
__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。
浙公网安备 33010602011771号