簡體   English   中英

在Objective-C中等效的接口類型?

[英]Interface Type Equivalent in Objective-C?

在Java中,我可以創建一個接口:

public interface SomeService {
   void test();
}

和一個實現此接口的類為:

public class SomeServiceImpl implements SomeService {
  @Override
  void test() {}
}

我在我的程序中可以執行以下操作:

SomeService service = new SomeServiceImpl();
service.test();

在Objective-C中是否存在等效項,以便我可以將接口作為變量類型?

那是一個協議

@protocol MyProtocol <NSObject>
-(void)test;
@end


@interface MyClass : NSObject <MyProtocol>

@end

@implementation MyClass
-(void) test
{
    ....
}
@end

可以將其分配給應實現MyProtocol的id類型的變量

id<MyProtocol> obj = [[MyClass alloc] init];
[obj test];

但這不必是id。 如果您需要實現特定協議的視圖控制器,請執行

UIViewController<MyProtocol> *vc = ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM