Last active
March 14, 2018 06:48
-
-
Save huaxinjiayou/71ca43baed7366e5640424994c5e34bc to your computer and use it in GitHub Desktop.
Aspects in Swift
This file contains hidden or 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
// https://github.com/steipete/Aspects | |
// usage | |
// NCLibBase.hook(object: UIViewController.self, selector: #selector(UIViewController.viewDidLoad), with: .after) { (aspect) in | |
// if let instance = aspect.instance() as? UIViewController { | |
// print("viewDidLoad") | |
// print(instance.description) | |
// } | |
// } | |
import Foundation | |
import Aspects | |
public struct NCLibBase { | |
public enum AspectOption: UInt { | |
case after = 0 | |
case instead = 1 | |
case before = 2 | |
case removal = 8 | |
var option: AspectOptions { | |
return AspectOptions(rawValue: rawValue) | |
} | |
} | |
@discardableResult | |
public static func hook(object: NSObject.Type, selector: Selector, with: AspectOption, block: @escaping (AspectInfo) -> Void) -> AspectToken? { | |
do { | |
return try object.aspect_hook(selector, with: with.option, usingBlock: wrap(aspect: block)) | |
} catch { | |
print(error) | |
return nil | |
} | |
} | |
@discardableResult | |
public static func hook(object: NSObject, selector: Selector, with: AspectOption, block: @escaping (AspectInfo) -> Void) -> AspectToken? { | |
do { | |
return try object.aspect_hook(selector, with: with.option, usingBlock: wrap(aspect: block)) | |
} catch { | |
print(error) | |
return nil | |
} | |
} | |
// util | |
private static func wrap(aspect: ((AspectInfo) -> Void)?) -> AnyObject { | |
let block:@convention(block) (AspectInfo)-> Void = { info in | |
if let aspect = aspect { | |
aspect(info) | |
} | |
} | |
let object: AnyObject = unsafeBitCast(block, to: AnyObject.self) | |
return object | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment