Flutter 混合原生工程内存泄露
最近启动新项目,以原生为基础框架,flutter为业务开发组件嵌入,混合开发过程中发现每次打开一个Flutter页面内存增加,关闭时内存并不释放,明显内存泄露。
解决方案一
问题出来了,到底是官方的问题,还是我这边代码的问题,深度探究并结合网上解决方案 修改引擎代码,修改引擎虽然解决了问题,但是每次官方发布新版本(如官方没解决)都需要重新编译引擎,相当麻烦。
解决方案二
混合开发内存泄露如果很普遍,官方应该会很快解决才对。
怀疑是不是自己代码有问题,一步步删除自己代码,发现如果自己不注册channel,单独使用flutterViewController并不会出现内存泄露,当注册methodChannel或eventChannel时出现内存泄露,原因上面方案已经有介绍并提供了方案解决。
转移思考:
第三方插件怎么实现,会内存泄露吗?是不是官方并不建议混合开发通过这种方式注册channel。
引入第三方flutter插件发现并不会内存泄露,解决方案出来了,去除自己注册channel方式
[FlutterChannelManager registerWithRegistry:self];
FlutterMethodChannel *flutterChannel = [FlutterMethodChannel methodChannelWithName:FLUTTER_METHOD_CHANNEL binaryMessenger:binaryMessenger];
[flutterChannel setMethodCallHandler:^(FlutterMethodCall * _Nonnull call, FlutterResult _Nonnull result) {
}];
}
采用插件式注册
[FlutterChannelManager registerWithRegistrar:[self registrarForPlugin:@"FlutterChannelManager"]];
FlutterMethodChannel *flutterChannel = [FlutterMethodChannel methodChannelWithName:FLUTTER_METHOD_CHANNEL binaryMessenger:[registrar messenger]];
FlutterChannelManager *instance = [[FlutterChannelManager alloc] init];
[registrar addMethodCallDelegate:instance channel:flutterChannel];
解决方案三
注册插件时,传入messageBinary为FlutterViewController的引擎,也能解决循环引用的问题
[FlutterChannelManager registeMethodChannel:self.engine];
FlutterChannelManager类实现registeMethodChannel:
+ (void)registeMethodChannel:(NSObject<FlutterBinaryMessenger> *) binaryMessenger {
FlutterMethodChannel *flutterChannel = [FlutterMethodChannel methodChannelWithName:FLUTTER_METHOD_CHANNEL binaryMessenger:binaryMessenger];
[flutterChannel setMethodCallHandler:^(FlutterMethodCall * _Nonnull call, FlutterResult _Nonnull result) {
}];
}
原因出在创建channel时,造成了循环引用,导致flutterViewController不释放。
这里只解决了FlutterViewController不调用dealloc方法,而且当我们需要调用开启的FlutterViewController经常会造成垂悬指针的导致Crash。