Skip to content

Commit bf65978

Browse files
committed
README: Code sample for object hook
1 parent 53f3a2c commit bf65978

File tree

2 files changed

+38
-21
lines changed

2 files changed

+38
-21
lines changed

README-legacy.md

Lines changed: 0 additions & 19 deletions
This file was deleted.

README.md

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -114,11 +114,47 @@ print(MyClass.getStaticValue()) // => 42
114114

115115
### Object Hook
116116

117-
117+
```swift
118+
class MyClass: NSObject {
119+
@objc dynamic func getValue() -> Int {
120+
return 42
121+
}
122+
}
123+
124+
let object1 = MyClass()
125+
let object2 = MyClass()
126+
127+
print(object1.getValue()) // => 42
128+
print(object2.getValue()) // => 42
129+
130+
let hook = try Interpose.applyHook(
131+
on: object1,
132+
for: #selector(MyClass.getValue),
133+
methodSignature: (@convention(c) (MyClass, Selector) -> Int).self,
134+
hookSignature: (@convention(block) (MyClass) -> Int).self
135+
) { hook in
136+
return { `self` in
137+
return hook.original(`self`, hook.selector) + 1
138+
}
139+
}
140+
141+
print(object1.getValue()) // => 43
142+
print(object2.getValue()) // => 42
143+
144+
try hook.revert()
145+
146+
print(object1.getValue()) // => 42
147+
print(object2.getValue()) // => 42
148+
```
149+
150+
> [!IMPORTANT]
151+
> If the object is already being observed via KVO when you apply or revert the hook, the operation will fail safely by throwing `InterposeError.kvoDetected(object:)`. Using KVO after the hook is installed is fully supported.
118152
119153
### More Examples
120154

121-
You can check out the extensive test suite to see more advanced examples or the example Xcode project to see more real-life examples of tweaking AppKit classes.
155+
You can check out the extensive test suite to see more advanced examples. The repository also comes with and example Xcode project, which showcases more real-life examples of tweaking AppKit classes.
156+
157+
<!-- Screenshot of example app -->
122158

123159
<h2 id="what-has-changed">What’s Changed</h2>
124160

0 commit comments

Comments
 (0)