Skip to content

Commit 9f20c03

Browse files
committed
Added KVO detection to the revert operation
1 parent 7d2bbea commit 9f20c03

File tree

2 files changed

+13
-1
lines changed

2 files changed

+13
-1
lines changed

Sources/InterposeKit/Hooks/HookStrategy/ObjectHookStrategy/ObjectHookStrategy.swift

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,10 @@ internal final class ObjectHookStrategy: HookStrategy {
151151
}
152152

153153
internal func restoreImplementation() throws {
154+
if object_isKVOActive(self.object) {
155+
throw InterposeError.kvoDetected(object: self.object)
156+
}
157+
154158
guard let hookIMP = self.appliedHookIMP else { return }
155159
guard let originalIMP = self.storedOriginalIMP else { return }
156160

Tests/InterposeKitTests/ObjectHookTests.swift

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,10 @@ final class ObjectHookTests: XCTestCase {
166166
_ = token
167167
}
168168

169-
// KVO works just fine on an object that has already been hooked.
169+
// KVO works on an object that was hooked earlier, but reverting the hook while an active
170+
// observer is installed fails. While it is technically possible to recover by stopping
171+
// the observation before reverting, the hook enters a failed state on error, preventing
172+
// it from accepting further operations.
170173
func testKVO_observationAfterHooking() throws {
171174
let object = ExampleClass()
172175

@@ -199,6 +202,11 @@ final class ObjectHookTests: XCTestCase {
199202
XCTAssertEqual(object.intValue, 3)
200203
XCTAssertEqual(didInvokeObserver, true)
201204

205+
XCTAssertThrowsError(
206+
try hook.revert(),
207+
expected: InterposeError.kvoDetected(object: object)
208+
)
209+
202210
_ = token
203211
}
204212

0 commit comments

Comments
 (0)