index.uts 1.6 KB
Newer Older
1 2
import { NotificationCenter } from 'Foundation';
import { UIApplication } from "UIKit"
3
import { Selector } from "ObjectiveC"
4
import { OnMemoryWarning, OffMemoryWarning, MemoryWarningCallback, MemoryWarningCallbackResult } from "../interface.uts"
5 6

class MemoryWarningTool {
7
  static listener: MemoryWarningCallback | null = null
DCloud_iOS_XHY's avatar
DCloud_iOS_XHY 已提交
8
	// 监听内存警告
9 10
	static listenMemoryWarning(callback: MemoryWarningCallback) {

11
		// 只有首次才需要注册监听事件
12
		if (this.listener == null) {
13 14 15 16 17
			// 注册监听内存警告通知事件及设置回调方法
			// target-action 回调方法需要通过 Selector("方法名") 构建
			const method = Selector("receiveMemoryWarning")
			NotificationCenter.default.addObserver(this, selector = method, name = UIApplication.didReceiveMemoryWarningNotification, object = null)
		}
18
    this.listener = callback
19
	}
20

21 22 23
	// 内存警告回调的方法
	// target-action 的方法前需要添加 @objc 前缀
	@objc static receiveMemoryWarning() {
DCloud_iOS_XHY's avatar
DCloud_iOS_XHY 已提交
24
		// 触发回调
25 26 27 28
   let res: MemoryWarningCallbackResult = {
     level: 0
   };
   this.listener?.(res);
29
	}
30

31
	// 移除监听事件
32 33 34
	static removeListen(callback: MemoryWarningCallback | null) {
    this.listener = null;
    NotificationCenter.default.removeObserver(this)
35 36 37
	}
}

38

39
// 开启监听内存警告
40
export const onMemoryWarning : OnMemoryWarning =  function (callback: MemoryWarningCallback) {
41 42 43 44
	MemoryWarningTool.listenMemoryWarning(callback)
}

// 关闭监听内存警告
45
export const offMemoryWarning : OffMemoryWarning = function (callback: MemoryWarningCallback | null) {
46
	MemoryWarningTool.removeListen(callback)
47
}