Ricardo de Cillo
Ricardo de Cillo

Reputation: 1164

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;

Am I right?

Upvotes: 1

Views: 184

Answers (4)

hooleyhoop
hooleyhoop

Reputation: 9198

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.

Upvotes: 2

DarkDust
DarkDust

Reputation: 92335

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.

Upvotes: 3

user557219
user557219

Reputation:

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];

Upvotes: 2

odrm
odrm

Reputation: 5259

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

Upvotes: 2

Related Questions