iosobjective-cswiftmethod-swizzling

Swizzling UIImage.init(named:) returns nil when getting the instance method


I am trying to swizzle UIImage init functions but when trying to get the instance function they return nil. Any idea?

let instance = class_getInstanceMethod(self, #selector(UIImage.init(named))
let instanceWithBundle = class_getInstanceMethod(self, #selector(UIImage.init(named:in:with)

Solution

  • It returns nil because in Objective-C they are actually class methods:

    +[UIImage imageNamed:]

    +[UIImage imageNamed:inBundle:withConfiguration:]

    Use class_getClassMethod instead (and make sure to add colons after named and with in your method selectors):

    let imageNamedMethod = class_getClassMethod(UIImage.self, #selector(UIImage.init(named:)))
    let imageNamedInWithMethod = class_getClassMethod(UIImage.self, #selector(UIImage.init(named:in:with:)))