cool hit counter Solving NSTimer's circular reference problem using blocks in iOS development_Intefrankly

Solving NSTimer's circular reference problem using blocks in iOS development


Copyright: This is an original post by the blogger and may not be reproduced without the blogger's permission. https://blog.csdn.net/u010105969/article/details/80313441

Circular reference issues.

Using an NSTimer object as a property of a controller, the current VC makes a strong reference to the NSTimer object. When the NSTimer is created to cash in, the NSTimer object in turn takes the current VC as its target, at which point the NSTimer object makes a strong reference to the current VC, thus creating a circular reference between the NSTimer and the current VC, which prevents both the VC and the NSTimer from being freed and eventually leads to a memory leak.

Usual code.

We can create a category for the NSTimer and add a method to the category that creates an NSTimer object to avoid the circular reference problem.

NSTimer Classification Code.

The code in the .m

Reproducible code.

  • (NSTimer *)resolve_scheduledTimerWithTimeInterval:(NSTimeInterval)inerval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block{ return [NSTimer scheduledTimerWithTimeInterval:inerval target:self selector:@selector(resolve_blcokInvoke:) userInfo:[block copy] repeats:repeats];

}

  • (void)resolve_blcokInvoke:(NSTimer *)timer { void (^block)(NSTimer *timer) = timer.userInfo; if (block) { block(timer); }

}

Use code.

Reproducible code.

weakifySelf self.timer = [NSTimer resolve_scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer *timer) { strongifySelf [self doThings]; NSLog(@"----------------"); }];

Regarding weakSelf and strongSelf.

define weakifySelf

__weak __typeof(&*self)weakSelf = self;

define strongifySelf

__strong __typeof(&*weakSelf)self = weakSelf;

Demo address.https://gitee.com/liangsenliangsen/nstimer_loop_reference.git That concludes this post, may you all work less overtime for more pay, and have girlfriends for all gays and boyfriends for all women.


Recommended>>
1、The Age of the Smart Connection of Everything Meritocracy in Philips display business
2、Youre buying this in the Strain so be careful
3、Xunlei Chain Caller Technology Shows the Prospects of Blockchain and Sharing Economy Integration
4、This beautiful programmer wrote the code that took man to the moon successfully
5、What is the technique of Guangdong Star Yue mahjong bullfighting

    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号