美文网首页
NSProxy定时器

NSProxy定时器

作者: 大冯宇宙 | 来源:发表于2019-10-24 19:17 被阅读0次

    NSProxy是一个专门用来消息转发的抽象类,发送给Proxy的消息会被转发给实际对象,或使Proxy加载(转化为)实际对象。NSProxy与NSObject同级别,没有父类。这里我们使用NSProxy写一个定时器,可以解决定时器的内存泄露问题。

    .h
    @interface XGProxy : NSProxy
    @property (nonatomic, weak) id target;
    + (instancetype)proxyWithTarget:(id)target;
    @end
    .m
    @implementation XGProxy
    + (instancetype)proxyWithTarget:(id)target {
        XGProxy * proxy = [XGProxy alloc];
        proxy.target = target;
        return proxy;
    }
    // 调用时候就会返回方法签名
    - (NSMethodSignature *)methodSignatureForSelector:(SEL)sel {
        return [self.target methodSignatureForSelector:sel];
    }
    // 进行消息转发
    - (void)forwardInvocation:(NSInvocation *)invocation {
        [invocation invokeWithTarget:self.target];
    }
    @end
    
    

    使用:

    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:[XGProxy proxyWithTarget:self] selector:@selector(timerS) userInfo:nil repeats:YES];
    }
    - (void)timerS {
    }
    - (void)dealloc {
        [self.timer invalidate];
    }
    @end
    

    相关文章

      网友评论

          本文标题:NSProxy定时器

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