Skip to content

Instantly share code, notes, and snippets.

@networkextension
Last active February 12, 2025 16:13
Show Gist options
  • Select an option

  • Save networkextension/70b0ae8a5602ab40443ef27bd1364d86 to your computer and use it in GitHub Desktop.

Select an option

Save networkextension/70b0ae8a5602ab40443ef27bd1364d86 to your computer and use it in GitHub Desktop.
demo Swift3 memory pressureEvent use DispatchSource API
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()
}
}
@eli-symbolab
Copy link
Copy Markdown

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, not source.mask. When I run the example I keep getting .all, which is indeed the mask we requested in makeMemoryPressureSource(eventMask:queue:).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment