Search code examples
iosobjective-cswiftobjective-c-category

Swift: How to call a category or class method from Objective-C


I have a category on UIImage that is written in Objective-C. The following are some example methods. How do I call these methods in Swift?

+(UIImage *) imageOrPDFNamed:(NSString *)resourceName; 
+(UIImage *) imageWithPDFNamed:(NSString *)resourceName;

I have tried the following and it does not recognize the methods:

let image = UIImage(imageOrPDFNamed:"test.pdf")
let image = UIImage(PDFNamed:"test.pdf")

Solution

  • There are various cases for categories function and it's calling conventions.

    1)In swift class functions in categories can be imported as convenience initializes if they returned same type on which they called like

     +(UIImage *) imageOrPDFNamed:(NSString *)resourceName ;
    

    so it can be called as

        UIImage(orPDFNamed: "abc")
    

    2)However if class functions in categories are not returning same object type(UIImage) on which it calls in this case UIImage like

       +(int) imageOrPDFNamedInt:(NSString *)resourceName ;
    

    it will called as

        UIImage.imageOrPDFNamedInt("abc")
    

    3)If categories function is not class function so it will call as directly on instance of UIImage like

       -(UIImage *) imagePDFNamed:(NSString *)resourceName ;
    

    called as

        UIImage().imagePDFNamed("abc")