美文网首页
iOS 定时器01

iOS 定时器01

作者: Smallwolf_JS | 来源:发表于2018-12-24 22:34 被阅读4次
    @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
    

    相关文章

      网友评论

          本文标题:iOS 定时器01

          本文链接:https://www.haomeiwen.com/subject/uabtlqtx.html