iOS 定时器01
2018-12-24 本文已影响4人
Smallwolf_JS
@interface MLProxy ()
@property (nonatomic, weak) id target;
@end
@implementation MLProxy
+ (instancetype)createProxyWeithTarget:(id)target{
MLProxy *proxy = [self alloc];
proxy.target = target;
return proxy;
}
- (id)forwardingTargetForSelector:(SEL)aSelector{
return self.target;
}
@end
- (void)viewDidLoad {
[super viewDidLoad];
self.proxy = [MLProxy createProxyWeithTarget:self];
// NSTimer
// 由于iOS的消息机制(objc_msgSend()), 系统会对self.proxy 发送一个scheduledTimerWithTimeInterval的消息由于MLProxyb并没有实现该方法,就会执行Runtime的消息转发机制。
self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self.proxy selector:@selector(timerAction) userInfo:nil repeats:YES];
}
自己创建的中间项
.h
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface XDProxy : NSProxy
/**
* 代理的对象
*/
@property (nonatomic,weak)id obj;
@end
NS_ASSUME_NONNULL_END
.m
#import "XDProxy.h"
@implementation XDProxy
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector{
NSMethodSignature *sig = nil;
sig = [self.obj methodSignatureForSelector:aSelector];
return sig;
}
/**
* NSInvocation封装了NSMethodSignature,通过invokeWithTarget方法将消息转发给其他对象.这里转发给控制器执行。
*/
- (void)forwardInvocation:(NSInvocation *)anInvocation{
[anInvocation invokeWithTarget:self.obj];
}
@end