iOS和flutter混编FlutterMethodChannel内存泄漏问题

1.前言

移动端原生和flutter模块混编时,少不了要在两个模块之间做通讯的需求。flutter为我们提供了三种交互方式:

  • BasicMessageChannel:双向通道,iOS和flutter都可以主动向对方传递消息,最简单的传递数据。

  • MethodChannel:双向通道,使用方式基本和BasicMessageChannel一样,但是高级一些,能够自定义methodName。

  • EventChannel:用于事件流的发送(event streams), 属于持续性的单向通信, 只能是 iOS 端主动调用, 常用于传递原生设备的信息, 状态等, 比如电池电量, 远程通知, 网络状态变化, 手机方向, 重力感应, 定位位置变化等等.

具体如何使用可以点击上方对应的链接查阅,这里不再赘述。本篇主要记录我在使用中遇到得一点问题和疑惑。

2.版本

当前使用的flutterdart版本如下:

flutter 2.8.1 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 77d935af4d (5 weeks ago) • 2021-12-16 08:37:33 -0800
Engine • revision 890a5fca2e
Tools • Dart 2.15.1

3.功能描述

很简单的一个测试功能:

  • 原生ViewController跳转到flutter模块,(即,present一个FlutterViewController)。
  • flutter模块点击左上角按钮触发MethodChannel,通知原生调用dismiss方法关闭flutter模块。

具体代码实现如下(只贴主要代码):

3.1原生代码

  • 为了方便查看对象是否销毁,这里继承一下官方的类,并重写deinit方法。

    class CusFlutterViewController: FlutterViewController {
        override init(engine: FlutterEngine, nibName: String?, bundle nibBundle: Bundle?) {
            super.init(engine: engine, nibName: nibName, bundle: nibBundle)
            self.modalPresentationStyle = .fullScreen
        }
        required init(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
        }
        deinit {
            debugPrint("deinit \(self)")
        }
    }
    
    class CusFlutterMethodChannel: FlutterMethodChannel {
        
        deinit {
            debugPrint("deinit \(self)")
        }
    }
    

    FlutterViewControllerFlutterMethodChannel被销毁时,控制台会打印出对应的日志。

  • 创建引擎,创建flutterViewContr,methodChannel,并实现回调。

    let flutterEngine = FlutterEngine(name: "my flutter engine")
    flutterEngine.run()
    GeneratedPluginRegistrant.register(with: flutterEngine);
    
    ...省略无关代码
    
    self.flutterVC = CusFlutterViewController.init(engine: flutterEngine, nibName: nil, bundle: nil)
    
    self.channel = CusFlutterMethodChannel.init(name: "channel", binaryMessenger: self.flutterVC!.binaryMessenger)
    
    self.channel?.setMethodCallHandler { [weak self] handler, block in
        let method = handler.method
        switch method {
        case "exit_flutter_module":
            self?.dismiss(animated: true, completion: {
                self?.channel?.setMethodCallHandler(nil)
                  self?.channel = nil
                  self?.flutterVC = nil
            })
        default:()
        }
    }
    
    self.present(self.flutterVC!, animated: true, completion: nil)
    

3.2 flutter端代码

点击按钮时,通知原生dismiss掉flutter模块

const MethodChannel flutterMethodChannel = MethodChannel('channel');

...省略无关代码
  
TextButton(
  child: const Text("back", style: TextStyle(color: Colors.red),),
  onPressed: () async {
    var result = await flutterMethodChannel.invokeMapMethod("exit_flutter_module") ?? {};
    debugPrint("$result");
  },
)

4.发现问题

当运行上述代码,从flutter模块返回原生页面时,发现控制台仅仅只输出了flutterViewController的deinit日志,而flutterMethodChanneldeinit方法并没有被触发。每次重新进入到flutter页面都会再次创建一个新的channel对象,但是返回时析构函数deinit并不会被触发。也就是说我重复N次进入和退出flutter页面时,内存中便创建了N个channel对象,他们都没有被释放掉。

个人具体探索问题的过程,这里就不赘述了,直接说说我的发现吧。将上文中创建channel的代码:

self.channel = CusFlutterMethodChannel.init(name: "channel", binaryMessenger: self.flutterVC!.binaryMessenger)

修改成:

self.channel = CusFlutterMethodChannel.init(name: "channel", binaryMessenger: self.flutterVC!.binaryMessenger, codec: FlutterStandardMethodCodec.sharedInstance())

上述的问题便解决了。从flutter页面返回原生界面时,channel的析构函数触发,控制台日志有输出。

5.疑惑

其实看官方注释的意思,两种构造方法方法区别不大:

/**
 * Creates a `FlutterMethodChannel` with the specified name and binary messenger.
 *
 * The channel name logically identifies the channel; identically named channels
 * interfere with each other's communication.
 *
 * The binary messenger is a facility for sending raw, binary messages to the
 * Flutter side. This protocol is implemented by `FlutterEngine` and `FlutterViewController`.
 *
 * The channel uses `FlutterStandardMethodCodec` to encode and decode method calls
 * and result envelopes.
 *
 * @param name The channel name.
 * @param messenger The binary messenger.
 */
+ (instancetype)methodChannelWithName:(NSString*)name
                      binaryMessenger:(NSObject<FlutterBinaryMessenger>*)messenger;

/**
 * Creates a `FlutterMethodChannel` with the specified name, binary messenger, and
 * method codec.
 *
 * The channel name logically identifies the channel; identically named channels
 * interfere with each other's communication.
 *
 * The binary messenger is a facility for sending raw, binary messages to the
 * Flutter side. This protocol is implemented by `FlutterEngine` and `FlutterViewController`.
 *
 * @param name The channel name.
 * @param messenger The binary messenger.
 * @param codec The method codec.
 */
+ (instancetype)methodChannelWithName:(NSString*)name
                      binaryMessenger:(NSObject<FlutterBinaryMessenger>*)messenger
                                codec:(NSObject<FlutterMethodCodec>*)codec;

第一个方法其实就是第二个方法codec默认为FlutterStandardMethodCodec。至于为何第一中方法构造的channel不能释放,只能去看源码才能解惑了。如果大家有好的想法和见解,还请不吝赐教!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,406评论 6 503
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,732评论 3 393
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,711评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,380评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,432评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,301评论 1 301
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,145评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,008评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,443评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,649评论 3 334
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,795评论 1 347
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,501评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,119评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,731评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,865评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,899评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,724评论 2 354