iOS NSTimer循環(huán)引用的3種解決方法

NSTimer使用時處理不好容易造成循環(huán)引用,導(dǎo)致控制器無法正常釋放。之前使用的方法或多或少都會在某些特定環(huán)境下造成一些問題。今天正好學(xué)習(xí)到了3種解決循環(huán)引用的方法,在這里記錄一下。

1.在didMoveToParentViewController:中取消NSTimer強引用

- (void)didMoveToParentViewController:(UIViewController *)parent{
    if (!parent) {
        [self.timer invalidate];
        self.timer = nil;
    }
}

2.利用target屬性和class_addMethod,使NSTimer不直接強引用self

@property (nonatomic , strong) id target;

_target = [NSObject new];
class_addMethod([_target class], @selector(update), (IMP)update, "v@:");
self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:_target selector:@selector(update) userInfo:nil repeats:YES];

void update(id self,SEL _cmd)
{
    NSLog(@"class_addMethod ----> update");
}

- (void)dealloc
{
    [self.timer invalidate];
    self.timer = nil;
}

3.利用NSProxy類(推薦)
YYText中就使用到了YYTextWeakProxy作為代理中間類。有興趣的可以去看看

//DEProxy.h
@interface DEProxy : NSProxy
@property (nonatomic , weak) id target;
@end


//DEProxy.m
@implementation DEProxy
//1.1.標(biāo)準(zhǔn)轉(zhuǎn)發(fā)-簽名
- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel
{
    return [_target methodSignatureForSelector:sel];
}
//1.2.標(biāo)準(zhǔn)轉(zhuǎn)發(fā)-轉(zhuǎn)發(fā)
- (void)forwardInvocation:(NSInvocation *)invocation{
    [invocation invokeWithTarget:_target];
}
//2.快速轉(zhuǎn)發(fā)
//- (id)forwardingTargetForSelector:(SEL)selector {
//    return _target;
//}
@end
//使用
@property (nonatomic , strong) DEProxy *targetProxy;

_targetProxy = [DEProxy alloc];
_targetProxy.target = self;
self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:_targetProxy selector:@selector(update) userInfo:nil repeats:YES];

-(void)update{
    NSLog(@"update");
}

- (void)dealloc
{
    [self.timer invalidate];
    self.timer = nil;
}

4.在iOS10以后,NSTimer新增了block方法來解決循環(huán)引用問題

    if (@available(iOS 10.0, *)) {
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
            NSLog(@"update");
        }];
    } else {
        // Fallback on earlier versions
    }

- (void)dealloc
{
    [self.timer invalidate];
    self.timer = nil;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容