Skip to content

Instantly share code, notes, and snippets.

@tonyarnold
Created September 11, 2020 04:34
Show Gist options
  • Save tonyarnold/dda01cec7eeae9ee2230f1f9ea60f976 to your computer and use it in GitHub Desktop.
Save tonyarnold/dda01cec7eeae9ee2230f1f9ea60f976 to your computer and use it in GitHub Desktop.

Revisions

  1. tonyarnold created this gist Sep 11, 2020.
    24 changes: 24 additions & 0 deletions NSObject+AnyCancellable.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,24 @@
    import Combine
    import ObjectiveC.runtime

    extension NSObject {
    private enum AssociatedKeys {
    static var CancellablesKey = "CancellablesKey"
    }

    /// A set that can be used to dispose of Combine cancellables.
    public var cancellables: Set<AnyCancellable> {
    get {
    if let cancellables = objc_getAssociatedObject(self, &NSObject.AssociatedKeys.CancellablesKey) {
    return cancellables as! Set<AnyCancellable>
    } else {
    let cancellables: Set<AnyCancellable> = []
    objc_setAssociatedObject(self, &NSObject.AssociatedKeys.CancellablesKey, cancellables, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
    return cancellables
    }
    }
    set {
    objc_setAssociatedObject(self, &NSObject.AssociatedKeys.CancellablesKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
    }
    }
    }