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

2020-03-08  本文已影响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];

}

上一篇下一篇

猜你喜欢

热点阅读