Objective-C 中的等效接口类型?
Interface Type Equivalent in Objective-C?
在java我可以创建一个界面:
public interface SomeService {
void test();
}
和一个 class 将此接口实现为:
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 = ...
在java我可以创建一个界面:
public interface SomeService {
void test();
}
和一个 class 将此接口实现为:
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 = ...