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

DCloud_iOS_XHY's avatar
DCloud_iOS_XHY 已提交
5 6
import { OffMemoryWarning, OnMemoryWarning, OnMemoryWarningCallback, OnMemoryWarningCallbackResult } from "../interface.uts"

7
class MemoryWarningTool {
DCloud_iOS_XHY's avatar
DCloud_iOS_XHY 已提交
8
	static listeners: OnMemoryWarningCallback[] = []
9
	
DCloud_iOS_XHY's avatar
DCloud_iOS_XHY 已提交
10
	// 监听内存警告
DCloud_iOS_XHY's avatar
DCloud_iOS_XHY 已提交
11
	static listenMemoryWarning(callback: OnMemoryWarningCallback) {
12
		
13 14 15 16 17 18 19 20
		// 只有首次才需要注册监听事件
		if (this.listeners.length == 0) {
			// 注册监听内存警告通知事件及设置回调方法
			// target-action 回调方法需要通过 Selector("方法名") 构建
			const method = Selector("receiveMemoryWarning")
			NotificationCenter.default.addObserver(this, selector = method, name = UIApplication.didReceiveMemoryWarningNotification, object = null)
		}
		this.listeners.push(callback)
21 22 23 24 25
	}
	
	// 内存警告回调的方法
	// target-action 的方法前需要添加 @objc 前缀
	@objc static receiveMemoryWarning() {
DCloud_iOS_XHY's avatar
DCloud_iOS_XHY 已提交
26
		// 触发回调
27
		this.listeners.forEach(listener => {
DCloud_iOS_XHY's avatar
DCloud_iOS_XHY 已提交
28 29
			const ret: OnMemoryWarningCallbackResult = {}
			listener(ret)
30
		})
31 32 33
	}
	
	// 移除监听事件
DCloud_iOS_XHY's avatar
DCloud_iOS_XHY 已提交
34
	static removeListen(callback: OnMemoryWarningCallback | null) {
35 36 37 38 39 40 41 42 43 44 45 46 47
		// 移除所有监听
		if (callback == null) {
			this.listeners = []
			// 移除监听事件
			NotificationCenter.default.removeObserver(this)
			return
		}
		
		// 清除指定回调
		const index = this.listeners.indexOf(callback!)
		if (index > -1) {
		    this.listeners.splice(index, 1)
		}
48 49 50 51
	}
}

// 开启监听内存警告
DCloud_iOS_XHY's avatar
DCloud_iOS_XHY 已提交
52
export const onMemoryWarning : OnMemoryWarning = function (callback: OnMemoryWarningCallback) {
53 54 55 56
	MemoryWarningTool.listenMemoryWarning(callback)
}

// 关闭监听内存警告
DCloud_iOS_XHY's avatar
DCloud_iOS_XHY 已提交
57
export const offMemoryWarning : OffMemoryWarning = function (callback: OnMemoryWarningCallback | null) {
58 59
	MemoryWarningTool.removeListen(callback)
}