Created
December 20, 2016 01:12
-
-
Save asaday/3f29d580293d9c948236b6e4b1ae9763 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public extension NSObject { | |
func removeNotifications() { | |
NSObject.cancelPreviousPerformRequests(withTarget: self) | |
NotificationCenter.default.removeObserver(self) | |
} | |
func addNotification(_ aSelector: Selector, key: String) { | |
NotificationCenter.default.addObserver(self, selector: aSelector, name: NSNotification.Name(rawValue: key), object: nil) | |
} | |
func addNotification(_ aSelector: Selector, name: Notification.Name) { | |
NotificationCenter.default.addObserver(self, selector: aSelector, name: name, object: nil) | |
} | |
var className: String { | |
guard let name = NSStringFromClass(type(of: self)).components(separatedBy: ".").last else { return "" } | |
return name | |
} | |
fileprivate struct AssociatedKeys { static var name = "name" } | |
func getAssociate(_ key: String) -> Any? { | |
guard let dic = objc_getAssociatedObject(self, &AssociatedKeys.name) as? [String: Any] else { return nil } | |
return dic[key] | |
} | |
func setAssociate(_ key: String, value: Any?) { | |
var dic = (objc_getAssociatedObject(self, &AssociatedKeys.name) as? [String: Any]) ?? [:] | |
dic[key] = value | |
objc_setAssociatedObject(self, &AssociatedKeys.name, dic, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) | |
} | |
} | |
public extension Notification { | |
static func post(key: String, object anObject: Any?) { | |
NotificationCenter.default.post(name: Notification.Name(rawValue: key), object: anObject) | |
} | |
static func post(name: Notification.Name, object anObject: Any?) { | |
NotificationCenter.default.post(name: name, object: anObject) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment