针对 Objective-C 中的接口而非实现进行设计
我一直在读一本关于 Objective-C 设计模式的书,很多次我读过类似的东西
id <AProtocol> obj;
,但我认为,在实践中,它并没有真正有用,原因很简单:在 iOS 中,你必须管理内存调用释放目的。如果您使用“id
”声明它,并且需要释放该对象,XCode 将警告您“release”方法不在该协议中。
所以更现实的方法是
NSObject <AProtocol> *obj;
我对吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
还有一个 NSObject 协议,因此您可以简单地定义:
这样 NSObject 的
retain
、release
等方法都是可见的。另请参阅此问题。There is also an NSObject protocol, so you can simply define:
That way the
retain
,release
, etc. methods of NSObject are visible. See also this question.不幸的是 NSObject*obj 无法编译。但是您可以告诉编译器您的对象符合
NSObject
协议。只需声明:如果您认为这太罗嗦,您可以在定义 NSObject 协议时将其“导入”到您的协议中:
Unfortunately
NSObject <AProtocol> *obj
won't compile. But you can tell the compiler that your object conforms to theNSObject
protocol. Just declare:If you think that's too wordy, you can "import" the NSObject protocol into yours when you define it:
您还可以使
AProtocol
本身符合NSObject
协议:通过这样做,编译器不会发出以下警告:
You can also make
AProtocol
itself conform to theNSObject
protocol:By doing that, the compiler won’t emit a warning for:
尽可能使用最具体的一个。如果您知道它是一个实例,请使用 NSObject *
NSObject 而不是 NSProxy。
如果您知道该实例是 NSView 的子类,请使用 NSView*。
然而,这与-release无关。如果您实际上需要协议来定义释放方法,也就是说,如果对象没有实现 NSObject 协议,则实现此接口是没有意义的,请在 AProtocol 的定义中包含 NSObject 协议,如 @Bvarious 所示。
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.