美文网首页
iOS 自定义NSTimer,解决析构问题

iOS 自定义NSTimer,解决析构问题

作者: 星之夜下 | 来源:发表于2020-03-08 13:42 被阅读0次

    思路:通过定义中间变量,解决内部的强引用问题。这样就可以解决了很多麻烦,使用起来也相对方便。

    #import "MyTimer.h"

    @interface MyTimer()

    @property(nonatomic,weak) id target;

    @property(nonatomic,assign) SEL aselector;

    @property(nonatomic,strong) NSTimer *mtimer;

    @end

    @implementation MyTimer

    + (instancetype)my_scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo{

        return [[MyTimer alloc] initScheduledTimerWithTimeInterval:ti target:aTarget selector:aSelector userInfo:userInfo repeats:yesOrNo];

    }

    - (instancetype)initScheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo{

        if(self== [superinit]) {

            self.target= aTarget;

            self.aselector= aSelector;

            self.mtimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(myTimerfunc) userInfo:nil repeats:YES];

        }

        return self;

    }

    -(void)myTimerfunc{

    #pragma clang diagnostic push

    #pragma clang diagnostic ignored"-Warc-performSelector-leaks"

       NSLog(@"---myTimerfunc");

        if ([self.target respondsToSelector:self.aselector]) {

            [self.targetperformSelector:self.aselector];

        }

    #pragma clang diagnostic pop

    }

    -(void)timer_invalidate{

        [self.mtimer invalidate];

        self.mtimer=nil;

    }

    @end


    在UIViewController中的使用:

    -(void)timerInit{

        self.mtimer1 = [MyTimer my_scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(myTimerfunc) userInfo:nil repeats:YES];

    }

    -(void)myTimerfunc{

        NSLog(@"---myTimerfunc");

    }

    - (void)dealloc

    {

        NSLog(@"---- %s",__func__);

        [self.mtimer1 timer_invalidate];

    }

    相关文章

      网友评论

          本文标题:iOS 自定义NSTimer,解决析构问题

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