index.uts 1.6 KB

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