Design to an interface not to an implementation in Objective-C
I've been reading a book about design patterns for Objective-C and many times I've read things like
id <AProtocol> obj;
But I think, in pratice, it's not really usable for a simple reason: in iOS you have to manage memory calling release on the object. If you declate it simple with "id <Protocol>
" and you need to release that obj, XCode is going to warn you that the "release" method is not in that protocol.
So a more reallistic approach would be
NSObject <AProtocol> *obj;
开发者_JAVA百科
Am I right?
There is also an NSObject protocol, so you can simply define:
@protocol AProtocol <NSObject>
That way the retain
, release
, etc. methods of NSObject are visible. See also this question.
Unfortunately NSObject <AProtocol> *obj
won't compile. But you can tell the compiler that your object conforms to the NSObject
protocol. Just declare:
id <NSObject,AProtocol> object;
If you think that's too wordy, you can "import" the NSObject protocol into yours when you define it:
@protocol AProtocol <NSObject>
// ...
@end
You can also make AProtocol
itself conform to the NSObject
protocol:
@protocol AProtocol <NSObject>
…
@end
By doing that, the compiler won’t emit a warning for:
id <AProtocol> obj;
…
[obj release];
Use the most specific one you can. Use NSObject * if you know it is an instance of NSObject and not, say, NSProxy.
Use NSView <AProtocol>*
if you know the instance is a subclass of NSView.
However this has nothing to do with -release. If you infact need to protocol to define the release method, that is, it makes no sense for an object to implement this interface if it doesn't also implement the NSObject protocol, include the NSObject protocol in the definition of AProtocol as @Bavarious demonstrates.
精彩评论