假设我们有以下 C++ 代码:
struct ISomeInterface
{
virtual ~ISomeInterface() {}
virtual void f() = 0;
};
class SomeClass : public ISomeInterface
{
public:
void f() override
{
std::cout << "Hi";
}
};
void getObject(ISomeInterface*& ptr)
{
ptr = new SomeClass;
}
int main()
{
ISomeInterface* p(nullptr);
getObject(p);
p->f();
delete p;
}
它非常简单,远非完美,但它描绘了一幅图画:通过函数的参数获取指向对象接口的指针。
我们如何在 Objective C 协议中得到相同的结果?
@protocol SomeProtocol <NSObject>
- (void)f;
@end
@interface SomeClass : NSObject<SomeProtocol>
- (void)f;
@end
@implementation SomeClass
- (void)f { NSLog(@"Hi"); }
@end
提前致谢。