Skip to content

Commit ef0fe2f

Browse files
committed
fix: crash of over-released when using Weak
1 parent 1f47ccc commit ef0fe2f

3 files changed

Lines changed: 12 additions & 3 deletions

File tree

Example/iOS_Example/iOS_Example/KeyboardManagerDemoViewController.swift

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ class KeyboardManagerDemoViewController: UIViewController {
1313

1414
deinit {
1515
print(#function)
16+
KeyboardManager.shared.removeObserver(self)
1617
}
1718

1819
var defaultFrame: CGRect = .zero

Sources/ReerKit/Utility/Weak/Weak.swift

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,10 +23,18 @@
2323
public final class Weak<T: AnyObject> {
2424
public private(set) weak var object: T?
2525
private let hashKey: Int
26+
2627
public init(_ object: T) {
2728
self.object = object
2829
self.hashKey = ObjectIdentifier(object).hashValue
2930
}
31+
32+
/// Creates a lookup-only instance that can be used for set operations
33+
/// without storing a weak reference. Useful when the object may be deallocating.
34+
public init(hashKeyOnly object: T) {
35+
self.object = nil
36+
self.hashKey = ObjectIdentifier(object).hashValue
37+
}
3038
}
3139

3240
extension Weak: Equatable, Hashable {

Sources/ReerKit/Utility/Weak/WeakSet.swift

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ public class WeakSet<T: AnyObject>: ExpressibleByArrayLiteral {
5353
}
5454

5555
public func contains(_ object: T) -> Bool {
56-
return objectSet.contains(Weak(object))
56+
return objectSet.contains(Weak(hashKeyOnly: object))
5757
}
5858

5959
public func add(_ object: T) {
@@ -74,11 +74,11 @@ public class WeakSet<T: AnyObject>: ExpressibleByArrayLiteral {
7474
}
7575

7676
public func remove(_ object: T) {
77-
objectSet.remove(Weak(object))
77+
objectSet.remove(Weak(hashKeyOnly: object))
7878
}
7979

8080
public func removeObjects(_ objects: [T]) {
81-
objectSet.subtract(objects.map { Weak($0) })
81+
objectSet.subtract(objects.map { Weak(hashKeyOnly: $0) })
8282
}
8383

8484
public func removeAll() {

0 commit comments

Comments
 (0)