Normally when developer makes a pointer to the instance of class which implements a protocol, she does this:
id<ProtocolName> myInstance = [[SomeClass alloc] init];
Is it OK to be more specific about the instance’s class type and use it like this?
SomeClass<ProtocolName> *myInstance = [[SomeClass alloc] init];
Or in method:
- (SomeClass<ProtocolName> *)someMethodWithArg:(int)arg;
With implementation (assume SomeSuperClass is superclass of SomeClass):
- (SomeClass<ProtocolName> *)someMethodWithArg:(int)arg
{
SomeClass<ProtocolName> *instance = [[SomeSuperClass alloc] init];
return instance;
}
Yes, it is OK. (Although I think your last example uses
SomeClasswhere it should be usingSomeSuperClass, but I understand what you meant.)In fact, sometimes you will need to do that. For example, to use
autoreleaseorreleaseon anNSObject(which is not available to anid<ProtocolName>(unlessProtocolNameexplicitly conforms to theNSObjectprotocol)), you would have to use: