Andrew  Lavq Andrew Lavq - 4 months ago 11
Objective-C Question

Getting protocol to an object via functions parameters

Let's say we have following C++ code:

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?

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

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

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


Thanks in advance.

Answer

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]));
    }
}