iOS NSTimer 的使用 -- 解决强引用的问题

NSTimer 的使用 ,主要是解决它在项目里使用时,经常导致的析构问题。直接上代发,比较简单。

#pragma mark---- 方法一

-(void)timerblock{

    self.mtimer = [NSTimer scheduledTimerWithTimeInterval:1.0 repeats:YES block:^(NSTimer * _Nonnull timer) {

//        NSLog(@"---%@",self); 这是循环引用问题

        NSLog(@"---mtimer");

    }];

}

- (void)dealloc

{

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

    [self.mtimer invalidate];

    self.mtimer=nil;

}

#pragma mark---- 方法二

-(void)timerInit{

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

}

-(void)myTimerfunc{

    NSLog(@"---myTimerfunc");

}

-(void)didMoveToParentViewController:(UIViewController *)parent{


    if(parent ==nil) {

        [self.mtimerinvalidate];

           self.mtimer=nil;

    }

}


#pragma mark---- 方法三,利用中间层


中间层定义类:

#import "MyProxy.h"

@interface MyProxy()

@property(nonatomic,weak) id objc;

@end

@implementation MyProxy

+ (instancetype)proxyTransformObjc:(id)object{

    MyProxy*proxy = [MyProxyalloc];

    proxy.objc= object;

    returnproxy;

}

-(NSMethodSignature *)methodSignatureForSelector:(SEL)sel{

    return [self.objc methodSignatureForSelector:sel];

}

-(void)forwardInvocation:(NSInvocation*)invocation{

    if(invocation) {

        [invocationinvokeWithTarget:self.objc];

    }else{

        NSLog(@" ---- 请注意stack");

    }

}

@end

在ViewController的使用:

-(void)timerInitproxy{

    self.mProxy = [MyProxy proxyTransformObjc:self];

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

}

-(void)myTimerfunc{

    NSLog(@"---myTimerfunc");

}

- (void)dealloc

{

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

    [self.mtimer invalidate];

    self.mtimer=nil;

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容