Skip to content

Instantly share code, notes, and snippets.

@mikeash
Created September 27, 2016 18:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikeash/1d216d2badf7c2d4430dd4fda008e933 to your computer and use it in GitHub Desktop.
Save mikeash/1d216d2badf7c2d4430dd4fda008e933 to your computer and use it in GitHub Desktop.
import Foundation
public func with<T>(_ item: T, update: (inout T) throws -> Void) rethrows -> T {
var this = item
try update(&this)
return this
}
class MyC: NSObject {
}
typealias RetainType = @convention(c) (UnsafeRawPointer, Selector) -> UnsafeRawPointer
let oldRetain = unsafeBitCast(class_getMethodImplementation_stret(MyC.self, sel_getUid("retain")), to: RetainType.self)
let retain: RetainType = { (self: UnsafeRawPointer, _cmd: Selector) -> UnsafeRawPointer in
print("Retaining")
return oldRetain(self, _cmd)
}
typealias ReleaseType = @convention(c) (UnsafeRawPointer, Selector) -> Void
let oldRelease = unsafeBitCast(class_getMethodImplementation_stret(MyC.self, sel_getUid("release")), to: ReleaseType.self)
let release: ReleaseType = { (self: UnsafeRawPointer, _cmd: Selector) -> Void in
print("Releasing")
oldRelease(self, _cmd)
}
class_addMethod(MyC.self, sel_getUid("retain"), unsafeBitCast(retain, to: IMP.self), "@@:")
class_addMethod(MyC.self, sel_getUid("release"), unsafeBitCast(release, to: IMP.self), "v@:")
while true {
let task3 = with(MyC()) { _ in
// $0.launchPath = "/usr/bin/mdfind"
// $0.arguments = ["kMDItemDisplayName == *.playground"]
// $0.standardOutput = pipe
// print($0)
}
// print(task3)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment