steipete / Aspects

Delightful, simple library for aspect oriented programming in Objective-C and Swift.
https://twitter.com/steipete
MIT License
8.4k stars 1.26k forks source link

how to hooking a class method? #157

Open sayHelloox opened 5 years ago

sayHelloox commented 5 years ago

I find some answer like https://github.com/steipete/Aspects/issues/20 https://github.com/steipete/Aspects/issues/27, but I found those can not work, do someone have other solution, thanks!

Assuner-Lee commented 5 years ago

id object = objectgetClass(obj); [object aspect...]

sayHelloox commented 5 years ago

can not work for me , What am wrong with me?

id object = object_getClass([TestObject new]);

[object aspect_hookSelector:@selector(testClassMethod) withOptions:AspectPositionAfter usingBlock:^(id<AspectInfo> info){
    NSLog(@"Class method ------ hook");

} error:NULL];

//then call method [TestObject testClassMethod];

// No log "Class method ------ hook" print

Assuner-Lee commented 5 years ago

id class = object_getClass(obj); id metaClass = objectgetClass(class); [metaClass aspect...]

shinyYangYang commented 4 years ago
  1. import <objc/runtime.h>

  2. fetch MetaClass Object

    Class settingsMetal = objc_getMetaClass(NSStringFromClass(Settings.class).UTF8String);

  3. hook with the MetaClass Object

    NSError error = nil; [settingsMetal aspect_hookSelector:@selector(hello:) withOptions:AspectPositionBefore usingBlock:^(id info, NSString hello){

    } error:&error]; NSLog(@"error %@", error);

Hope this help you !