Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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")
like image 266
RawMean Avatar asked Aug 01 '14 21:08

RawMean


2 Answers

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")
like image 193
codester Avatar answered Oct 21 '22 11:10

codester


This is finally what worked:

let image = UIImage(orPDFNamed:"test.pdf")
like image 31
RawMean Avatar answered Oct 21 '22 09:10

RawMean