针对 Objective-C 中的接口而非实现进行设计

发布于 2024-11-01 11:03:10 字数 332 浏览 1 评论 0原文

我一直在读一本关于 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

2024-11-08 11:03:10

还有一个 NSObject 协议,因此您可以简单地定义:

@protocol AProtocol <NSObject>

这样 NSObject 的 retainrelease 等方法都是可见的。另请参阅此问题

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.

音盲 2024-11-08 11:03:10

不幸的是 NSObject*obj 无法编译。但是您可以告诉编译器您的对象符合NSObject协议。只需声明:

id <NSObject,AProtocol> object;

如果您认为这太罗嗦,您可以在定义 NSObject 协议时将其“导入”到您的协议中:

@protocol AProtocol <NSObject>
// ...
@end

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
情魔剑神 2024-11-08 11:03:10

您还可以使 AProtocol 本身符合 NSObject 协议:

@protocol AProtocol <NSObject>
…
@end

通过这样做,编译器不会发出以下警告:

id <AProtocol> obj;
…
[obj release];

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];
花开柳相依 2024-11-08 11:03:10

尽可能使用最具体的一个。如果您知道它是一个实例,请使用 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文