NSProxy
NSProxy并不继承与NSObject,它是一个虚类,并遵守NSObject协议。你需要继承NSProxy,并实现NSObject协议中的
- (void)forwardInvocation:(NSInvocation *)anInvocation
- (id)forwardingTargetForSelector:(SEL)selector
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector的方法
消息重定向
与- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector对应的是
+ (NSMethodSignature *)instanceMethodSignatureForSelector:(SEL)aSelector,来获取类方法的地址
利用NSProxy做NSTmer和CADisplayLink的target
@interface WeakProxy : NSProxy
@property (nonatomic,weak,readonly)id target;
- (instancetype)initWithTarget:(id)target;
+ (instancetype)proxyWithTarget:(id)target;
@end
@implementation WeakProxy
- (instancetype)initWithTarget:(id)target {
_target = target;
returnself;
}
+ (instancetype)proxyWithTarget:(id)target {
return [[KHWeakProxyalloc]initWithTarget:target];
}
- (id)forwardingTargetForSelector:(SEL)selector {
return_target;
}
- (void)forwardInvocation:(NSInvocation *)invocation {
void *null = NULL;
[invocation setReturnValue:&null];
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)selector {
return [NSObjectinstanceMethodSignatureForSelector:@selector(init)];
}
- (BOOL)respondsToSelector:(SEL)aSelector {
return [_targetrespondsToSelector:aSelector];
}
- (BOOL)isProxy {
returnYES;
}
@end
由于NSProxy并没有init的方法,所以我们在使用的时候并不能调用init方法,我们在methodSignatureForSelector:中调用NSObject的init方法来初始化我们WeakProxy。
使用方法:
@Interface TestProxy: NSObject
@property (strong,nonatomic)NSTimer *timer;
@end
@implementation
- (void) startTimer {
_timer = [NSTimerscheduledTimerWithTimeInterval:1
target:[KHWeakProxyproxyWithTarget:self]
selector:@selector(countDown)
userInfo:nil
repeats:YES];
}
- (void)countDown {
//your code...
}
@end