Reputation: 198
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;
}
Upvotes: 3
Views: 740
Reputation: 990
Yes, it is OK. (Although I think your last example uses SomeClass
where it should be using SomeSuperClass
, but I understand what you meant.)
In fact, sometimes you will need to do that. For example, to use autorelease
or release
on an NSObject
(which is not available to an id<ProtocolName>
(unless ProtocolName
explicitly conforms to the NSObject
protocol)), you would have to use:
NSObject<ProtocolName> *protoObj = [....];
[....]
[protoObj autorelease];
Upvotes: 3