Last active
February 12, 2025 16:13
-
-
Save networkextension/70b0ae8a5602ab40443ef27bd1364d86 to your computer and use it in GitHub Desktop.
demo Swift3 memory pressureEvent use DispatchSource API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import Foundation | |
| class A { | |
| var d:[Int]? | |
| init(len:Int) { | |
| d = Array(repeating: 0, count: len) | |
| } | |
| } | |
| func test() { | |
| installMemoryWarning() | |
| var b :[A] = [] | |
| for _ in 0 ... 2000 { | |
| let c = A.init(len: 1024 * 1000*3 ) | |
| b.append(c) | |
| sleep(1) | |
| } | |
| } | |
| func installMemoryWarning(){ | |
| let source = DispatchSource.makeMemoryPressureSource(eventMask: .all, queue: nil) | |
| let q = DispatchQueue.init(label: "test") | |
| q.async { | |
| source.setEventHandler { | |
| let event:DispatchSource.MemoryPressureEvent = source.mask | |
| print(event) | |
| switch event { | |
| case DispatchSource.MemoryPressureEvent.normal: | |
| print("normal") | |
| case DispatchSource.MemoryPressureEvent.warning: | |
| print("warning") | |
| case DispatchSource.MemoryPressureEvent.critical: | |
| print("critical") | |
| default: | |
| break | |
| } | |
| } | |
| source.resume() | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, thanks for this useful snippet! Especially as I've been having a hard time finding an official Apple source for this.
It seems like line 28 should be getting the
source.data, notsource.mask. When I run the example I keep getting.all, which is indeed the mask we requested inmakeMemoryPressureSource(eventMask:queue:).