gpt4 book ai didi

java - Objective-C 中的接口(interface)类型等效吗?

转载 作者:行者123 更新时间:2023-12-01 18:18:09 24 4
gpt4 key购买 nike

在java中我可以创建一个接口(interface):

public interface SomeService {
void test();
}

以及一个实现此接口(interface)的类:

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

我的程序我可以做这样的事情:

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

Objective-C 中是否有等效项,以便我可以将接口(interface)作为变量类型?

最佳答案

这是一个协议(protocol)

@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。如果您需要一个实现特定协议(protocol)的 View Controller ,请执行

UIViewController<MyProtocol> *vc = ...

关于java - Objective-C 中的接口(interface)类型等效吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28382974/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com