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

235 views Asked by At

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)
1

There are 1 answers

3
TylerP On BEST ANSWER

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:)))