如何在objective-c中使用“interface”

时间:2021-07-27 17:44:30

I need to create a class that will have the same methods as other class. In Java or ActionScript there would be an interface that my class will implement but how I can achieve this in objective-c?

我需要创建一个与其他类具有相同方法的类。在Java或ActionScript中,我的类将实现一个接口但是如何在objective-c中实现这一点?

I want to create custom UIProgressView without extending this class but have the same public methods (interface).

我想创建自定义UIProgressView而不扩展此类,但具有相同的公共方法(接口)。

3 个解决方案

#1


2  

You can use @protocol, this works similar as java interface:

您可以使用@protocol,这与java接口类似:

@protocol MyProtocol
-(void)method1;
-(void)method2WithParameter:(NSString*)parameter;
@end

In the classes you want to implement this methods you need to conform to that protocol:

在要实现此方法的类中,您需要符合该协议:

@interface ViewController : UIViewController <MyProtocol>

and you need to implement the required methods.

你需要实现所需的方法。

#2


2  

You can use a protocol.

您可以使用协议。

See this Apple Guide.

请参阅此Apple指南。

#3


2  

Interface are called a protocol in objective-c.

接口在objective-c中称为协议。

@protocol SomeDelegate <NSObject>

- (void)someMethod;

@optional
- (void)someOptionalMethod:(NSString *)name;
@end

To use the interface just add it to you class like: @interafce MyClass: NSObject<SomeDelegate>.

要使用该接口,只需将其添加到类中:@interafce MyClass:NSObject

If you are not sure, at runtime if the method exists, just should check it with respondsToSelector::

如果您不确定,在运行时如果该方法存在,则应该使用respondsToSelector ::

 if([self.instanceOfMyClass respondsToSelector:@selector(someOptionalMethod:)]) {
    [self.instanceOfMyClass someOptionalMethod:@"my parameter"]
 }

#1


2  

You can use @protocol, this works similar as java interface:

您可以使用@protocol,这与java接口类似:

@protocol MyProtocol
-(void)method1;
-(void)method2WithParameter:(NSString*)parameter;
@end

In the classes you want to implement this methods you need to conform to that protocol:

在要实现此方法的类中,您需要符合该协议:

@interface ViewController : UIViewController <MyProtocol>

and you need to implement the required methods.

你需要实现所需的方法。

#2


2  

You can use a protocol.

您可以使用协议。

See this Apple Guide.

请参阅此Apple指南。

#3


2  

Interface are called a protocol in objective-c.

接口在objective-c中称为协议。

@protocol SomeDelegate <NSObject>

- (void)someMethod;

@optional
- (void)someOptionalMethod:(NSString *)name;
@end

To use the interface just add it to you class like: @interafce MyClass: NSObject<SomeDelegate>.

要使用该接口,只需将其添加到类中:@interafce MyClass:NSObject

If you are not sure, at runtime if the method exists, just should check it with respondsToSelector::

如果您不确定,在运行时如果该方法存在,则应该使用respondsToSelector ::

 if([self.instanceOfMyClass respondsToSelector:@selector(someOptionalMethod:)]) {
    [self.instanceOfMyClass someOptionalMethod:@"my parameter"]
 }