MacRuby:符合协议
我是 MacRuby(和 Objective-C)的新手。阅读一些 Cocoa 文档,我不断遇到提到遵守协议的代表的部分。到目前为止,我一直将我的 AppDelegate
设置为任何涉及委托的协议,但我不确定我是否遵守了必要的协议。
关于协议我需要了解哪些内容以及如何在我的应用程序中遵守这些协议?
I'm new to MacRuby (and Objective-C). Reading through some of the Cocoa documentation, I keep coming across parts that mention delegates conforming to protocols. So far, I keep setting my AppDelegate
as the protocol for anything that talks about a delegate, but I'm not sure whether or not I'm conforming to the necessary protocols.
What do I need to know about Protocols and how do I conform to them in my application?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要了解什么是[正式] Objective-C 协议,包括它定义了强制和/或可选方法。请参阅 Apple 的 Objective-C 文档。协议是多重继承的有限形式,其中仅继承行为,而不继承状态。其他语言可能会调用该
接口
或mix-in
。遵守协议意味着您的类实现了所有强制方法,也可能没有实现,也可能实现部分或全部可选方法。
通常,协议用于代表。它是一种形式化类从其委托所需的 API 的方法。对于给定的委托协议,您需要了解该 API。请参阅有关该特定协议的 Apple 文档。
最后,您既没有办法也没有必要声明您的 MacRuby 类符合任何协议。您可以直接将类实例分配给客户端对象委托。您仍然需要遵守协议,但不会进行任何编译时检查。如果未能符合要求,则可能会出现运行时异常。或者一些奇怪的行为。或者什么。
无论如何,这就是我的理解。
You need to understand what an [formal] Objective-C protocol is, including that it defines mandatory and/or optional methods. See Apple's Objective-C documentation. Protocols are a limited form of multiple inheritance whereby only behavior, but not state, is inherited. Other languages may call that
interface
ormix-in
.To conform to a protocol means that your class implements all mandatory methods, and possibly none, some or all optional methods.
Typically, protocol are used for delegates. It's a means to formalize the API that a class requires from its delegate. For a given delegate protocol, you need to understand that API. Refer to Apple's documentation regarding that specific protocol.
Finally, there is neither a way nor a need for you to declare that your MacRuby class conforms to any protocol. You can directly assign your class instance to the client object delegate. You are still required to conform to the protocol, but there won't be any compile-time checking. If you fail conforming, you can expect a run-time exception. Or some odd behavior. Or something.
That's my understanding anyway.