Swift:如何从Objective-C调用类或类方法

时间:2023-01-15 14:11:37

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上有一个用Objective-C编写的类别。以下是一些示例方法。如何在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")

2 个解决方案

#1


13  

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

1)在swift类中,如果返回类别中的函数,则可以导入类别中的函数,因为它们返回了相同的类型

 +(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

2)但是如果类别中的类函数没有返回它调用的相同对象类型(UIImage),在这种情况下UIImage就像

   +(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

3)如果categories函数不是类函数,那么它将直接调用UIImage的实例

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

called as

叫做

    UIImage().imagePDFNamed("abc")

#2


1  

This is finally what worked:

这最终是有效的:

let image = UIImage(orPDFNamed:"test.pdf")

#1


13  

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

1)在swift类中,如果返回类别中的函数,则可以导入类别中的函数,因为它们返回了相同的类型

 +(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

2)但是如果类别中的类函数没有返回它调用的相同对象类型(UIImage),在这种情况下UIImage就像

   +(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

3)如果categories函数不是类函数,那么它将直接调用UIImage的实例

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

called as

叫做

    UIImage().imagePDFNamed("abc")

#2


1  

This is finally what worked:

这最终是有效的:

let image = UIImage(orPDFNamed:"test.pdf")