简体   繁体   English

通过函数参数获取对象的协议

[英]Getting protocol to an object via functions parameters

Let's say we have following C++ code: 假设我们有以下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;
}

It's quite straightforward and far from being perfect, but it draws the picture: getting a pointer to an interface to an object via function's parameters. 它非常简单,远非完美,但它画出了一个图:通过函数的参数获取指向对象接口的指针。

How do we get the same with Objective C protocols? 我们如何使用Objective C协议获得相同的结果?

@protocol SomeProtocol <NSObject>
- (void)f;
@end

@interface SomeClass : NSObject<SomeProtocol>
- (void)f;
@end

@implementation SomeClass
- (void)f { NSLog(@"Hi"); }
@end

Thanks in advance. 提前致谢。

C-style function: C风格的功能:

id<SomeProtocol> getObject()
{
    return [SomeClass new];
}

Objective-C (class) function: Objective-C(类)功能:

@implementation SomeOtherClass

+ id<SomeProtocol> getObject
{
    return [SomeClass new];
}

@end

If you actually want the reference parameter, you can do: 如果您确实需要引用参数,则可以执行以下操作:

void getObject(id<SomeProtocol> *ptr)
{
    if (ptr) {
        *ptr = [[SomeClass alloc] init];
    }
}

int main(int argc, char *argv[])
{
    @autoreleasepool {
        id<SomeProtocol> p = nil;
        getObject(&p);
        [p f];
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM