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

2

5

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")
Pteridophyte answered 1/8, 2014 at 21:45 Comment(2)
These are class methods; UIImage.image...Michellemichels
Also make sure you've #imported the category's header in your bridging header.Throng
Y
14

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")
Yesseniayester answered 1/8, 2014 at 21:54 Comment(4)
This didn't work, but your answer helped me find the solution in the sense that after entering your suggested code, Xcode said this method is not available and then suggested the code that I am showing in my answer.Pteridophyte
@Pteridophyte thanks for pointing that actually i have ignored on which it is called.Sorry for that.Howerver i have edited my answer it will further clarifies how to call category function in swift.Yesseniayester
Your answer before the "edit" is still incorrect. I'd like to accept your answer if you can remove the bit before the "Edit"Pteridophyte
Good answer. Seems that if your category class method is something like + (NSDate *)dateWithTimestamp:(NSString *)timestamp then the convenience initializer assumes the "with" as well, so it is called like this: NSDate(timestamp:timestampString). That seems less than obvious, and it is unclear to me why I can't just use NSDate.dateWithTimestamp(...) if I want to. Convenience initializers are not a convenience if they're mandatory.Ingram
P
1

This is finally what worked:

let image = UIImage(orPDFNamed:"test.pdf")
Pteridophyte answered 2/8, 2014 at 15:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.