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;
}