循环引证常见原因:
一、 当前VC
运用了NSTimer
, 并没有对它进行毁掉.
Tips:在计时完毕或者脱离页面的时分,毁掉timer
,步骤如下:
if(_timer) {
[_timer invalidate];
_timer = nil;
}
二、block
块内运用了self
,形成了循环引证.
Tips1:一般的系统办法或者类办法不会形成循环引证,并不是一切的
block
都会形成循环引证,一般只有实例办法的block
块内,调用了self
的办法才会形成循环引证
Tips2:调用了
performSelector
延迟办法的,dealloc
办法会延迟履行 利用如下函数能够处理:[NSObject cancelPreviousPerformRequestsWithTarget:self];
或[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(method1:) object:nil];
Tips3: 常见自定义
cell
里面的block循环引证 处理方案:1.运用__weak typeof(self) weakSelf = self;
打断循环引证2.假如忧虑
self
在block
内提前开释,可用如下处理办法
@weakify(self);
cell.didTag = ^(NSInteger tag) {
@strongify(self);
[self didJianGuanTag:tag];
};
三、运用delegate
, 用了strong
润饰,要运用weak
来润饰.
@property(nonatomic, weak) id<WEBidListTableViewCellDelegate>delegate;
四、NSNotificationCenter
运用 block
注册addObserver(forName:object:queue:using:)
,但是没有在dealloc中移除;
假如在block内运用了self,就要打破循环引证:
@weakify(self);
[[NSNotificationCenter defaultCenter]addObserverForName:@"RefreshMySelectImg" object:nil queue:nil usingBlock:(NSNotification *_Nonnull note) {
@strongify(self);
[self.tableView reloadData];
}];
五、vc
中运用了WKWebView
调用addScriptMessageHandler
形成了循环引证.
前言定论:在与H5进行交互时,常常运用
addScriptMessageHandler
增加参数信息,它需要增加一个userContentController
署理目标;self
强引证- >WKWebView
– >configuration
参数 ->userContentController
2.userContentController
强引证 – >self
处理方案1.在viewWillAppear
办法中增加 addScriptMessageHandler
,在viewWillDisappear
办法中移除调用
处理方案2. 打断循环引证,具体如下调用运用
- (void)addJSHandler {
id webViewSelf = [[WeakScriptMessageDelegate alloc] initWithDelegate:self];
[self.webView.configuration.userContentController addScriptMessageHandler:webViewSelf name:@"js_close"];
}
// WeakScriptMessageDelegate.h
#import <Foundation/Foundation.h>
@interface WeakScriptMessageDelegate : NSObject <WKScriptMessageHandler>
@property (nonatomic, weak) id<WKScriptMessageHandler> scriptDelegate;
- (instancetype)initWithDelegate:(id<WKScriptMessageHandler>)scriptDelegate;
@end
// WeakScriptMessageDelegate.m
#import "WeakScriptMessageDelegate.h"
@implementation WeakScriptMessageDelegate
- (instancetype)initWithDelegate:(id<WKScriptMessageHandler>)scriptDelegate {
self = [super init];
if (self) {
_scriptDelegate = scriptDelegate;
}
return self;
}
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
[self.scriptDelegate userContentController:userContentController didReceiveScriptMessage:message];
}
@end
:保持杰出的代码习惯很重要