Question

I'm trying to accomplish something like the following:

- (id<SomeProtocol>)instanceFromClass:(Class<SomeProtocol>)cls
{
    return [[cls alloc] initUsingSomeConstructorDefinedInProtocolWithValue:_value];
}

However, I'm getting a No Known class method for selector 'alloc' error. How may I specify in my signature that I want to receive a class that conforms to a protocol? Or, if that part is correct, how may I create an instance from that argument using a constructor defined in the specified protocol?

Was it helpful?

Solution

Not sure why the compiler complains but you can fix by casting your parameter back to Class

- (id<SomeProtocol>)instanceFromClass:(Class<SomeProtocol>)cls
{
    return [[(Class)cls alloc] initUsingSomeConstructorDefinedInProtocolWithValue:_value];
}

while still getting you the type checking you want for the parameter as hinted at in this SO answer: Declare an ObjC parameter that's a Class conforming to a protocol

OTHER TIPS

Your use of the protocol is 'fine'. The issue is that the cls parameter is tagged as a class which conforms to a protocol that defines instance methods (the init method). This doesn't tell the compiler that the +alloc method is available because that is a class method on NSObject.

You can add the +alloc method to the protocol. Or you can do some casting to tell the compiler to trust you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top