提交 6deca516 编写于 作者: DCloud_iOS_XHY's avatar DCloud_iOS_XHY

更新 iOS 平台内存警告插件,支持多个监听

上级 ca0a8cd6
...@@ -3,35 +3,50 @@ import { UIApplication } from "UIKit" ...@@ -3,35 +3,50 @@ import { UIApplication } from "UIKit"
import { Selector } from "ObjectiveC" import { Selector } from "ObjectiveC"
class MemoryWarningTool { class MemoryWarningTool {
static listener: UTSCallback | null; static listeners: UTSCallback[] = []
// 监听内存警告 // 监听内存警告
static listenMemoryWarning(callback: UTSCallback | null) { static listenMemoryWarning(callback: UTSCallback) {
this.listener = callback
// 注册监听内存警告通知事件及设置回调方法 // 只有首次才需要注册监听事件
// target-action 回调方法需要通过 Selector("方法名") 构建 if (this.listeners.length == 0) {
const method = Selector("receiveMemoryWarning") // 注册监听内存警告通知事件及设置回调方法
NotificationCenter.default.addObserver(this, selector = method, name = UIApplication.didReceiveMemoryWarningNotification, object = null) // target-action 回调方法需要通过 Selector("方法名") 构建
const method = Selector("receiveMemoryWarning")
NotificationCenter.default.addObserver(this, selector = method, name = UIApplication.didReceiveMemoryWarningNotification, object = null)
}
this.listeners.push(callback)
} }
// 内存警告回调的方法 // 内存警告回调的方法
// target-action 的方法前需要添加 @objc 前缀 // target-action 的方法前需要添加 @objc 前缀
@objc static receiveMemoryWarning() { @objc static receiveMemoryWarning() {
// 触发回调 // 触发回调
this.listener?.({}) this.listeners.forEach(listener => {
listener({})
})
} }
// 移除监听事件 // 移除监听事件
static removeListen(callback: UTSCallback | null) { static removeListen(callback: UTSCallback | null) {
this.listener = null // 移除所有监听
NotificationCenter.default.removeObserver(this) if (callback == null) {
callback?.({}) this.listeners = []
// 移除监听事件
NotificationCenter.default.removeObserver(this)
return
}
// 清除指定回调
const index = this.listeners.indexOf(callback!)
if (index > -1) {
this.listeners.splice(index, 1)
}
} }
} }
// 开启监听内存警告 // 开启监听内存警告
export function onMemoryWarning(callback: UTSCallback | null) { export function onMemoryWarning(callback: UTSCallback) {
MemoryWarningTool.listenMemoryWarning(callback) MemoryWarningTool.listenMemoryWarning(callback)
} }
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册