2015-02-07 39 views
0

在java中我可以创建一个接口:Objective-C中的接口类型等效吗?

public interface SomeService { 
    void test(); 
} 

和一个类实现此接口为:

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

我我的计划,我可以做这样的事情:

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

Objective-C中是否存在一个等价物,以便我可以将Interface作为变量类型?

回答

4

这是一个协议

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


@interface MyClass : NSObject <MyProtocol> 

@end 

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

可以分配到应实施MyProtocol

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

但它并不一定是ID ID类型的变量。如果您需要实现特定协议的视图控制器,请执行以下操作:

UIViewController<MyProtocol> *vc = ...