Search code examples
objective-cclassprotocols

Create an instance from a Class that conforms to a Protocol


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?


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