index.uts 1.2 KB
Newer Older
1 2
import { NotificationCenter } from 'Foundation';
import { UIApplication } from "UIKit"
3
import { Selector } from "ObjectiveC"
4 5 6 7

class MemoryWarningTool {
	static listener: UTSCallback | null;
	
DCloud_iOS_XHY's avatar
DCloud_iOS_XHY 已提交
8
	// 监听内存警告
9 10 11
	static listenMemoryWarning(callback: UTSCallback | null) {
		this.listener = callback
		
DCloud_iOS_XHY's avatar
DCloud_iOS_XHY 已提交
12
		// 注册监听内存警告通知事件及设置回调方法
13 14 15 16 17 18 19 20
		// target-action 回调方法需要通过 Selector("方法名") 构建
		const method = Selector("receiveMemoryWarning")
		NotificationCenter.default.addObserver(this, selector = method, name = UIApplication.didReceiveMemoryWarningNotification, object = null)
	}
	
	// 内存警告回调的方法
	// target-action 的方法前需要添加 @objc 前缀
	@objc static receiveMemoryWarning() {
DCloud_iOS_XHY's avatar
DCloud_iOS_XHY 已提交
21
		// 触发回调
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
		this.listener?.({})
	}
	
	// 移除监听事件
	static removeListen(callback: UTSCallback | null) {
		this.listener = null
		NotificationCenter.default.removeObserver(this)
		callback?.({})
	}
}

// 开启监听内存警告
export function onMemoryWarning(callback: UTSCallback | null) {
	MemoryWarningTool.listenMemoryWarning(callback)
}

// 关闭监听内存警告
export function offMemoryWarning(callback: UTSCallback | null) {
	MemoryWarningTool.removeListen(callback)
}