菜鸟教程小白 发表于 2022-12-13 05:55:32

ios - 当已知对象符合协议(protocol)时,断言对象包含某些方法是一种好的模式吗?


                                            <p><p>出于我项目 UI 的目的,我正在 UIViewController 上的一个类别中创建一个通用方法,该方法为导航项设置 UI。这个特定的导航项有一个对应于操作(保存、确定、选择等)的黄色按钮和一个灰色按钮(取消、关闭)</p>

<pre><code>- (void)configureAsSaveCancelIPadHeaderWithTarget:(id)theTarget actionForYellowButton:(SEL)selYellow actionForGrayButton:(SEL)selGray
</code></pre>

<p>我想我可以像这样使这个方法更小:</p>

<pre><code>- (void)configureAsSaveCancelIPadHeaderWithTarget:(id&lt;PSaveCancelViewControllerNavigationBar&gt;)theTarget
</code></pre>

<p>并让目标响应协议(protocol)。</p>

<p>协议(protocol)如下所示:</p>

<pre><code>@protocol PSaveCancelViewControllerNavigationBar &lt;NSObject&gt;
@required
- (void)save:(id)sender;
- (void)closeThisView:(id)sender;
@end
</code></pre>

<p><code>@required</code> 关键字只会在这两种方法未实现时发出警告。</p>

<p><strong>问题</strong></p>

<p>如果目标包含这两个方法,那么在 <code>configureAsSaveCancelIPadHeaderWithTarget:</code> 方法中断言是否被认为是一种好的模式?像这样:</p>

<pre><code>    - (void)configureAsSaveCancelIPadHeaderWithTarget:(id&lt;PSaveCancelViewControllerNavigationBar&gt;)theTarget
{
    NSAssert(, @&#34;The provided target must implement the PSaveCancelViewControllerNavigationBar protocol and have the methods defined in that protocol.&#34;);
    NSAssert(, @&#34;The provided target must implement the PSaveCancelViewControllerNavigationBar protocol and have the methods defined in that protocol.&#34;);
</code></pre>

<p>我以后肯定会调用这两个方法(save、closeThisView),所以我必须确保调用这个方法的类已经实现了它们。</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>这一切都取决于您想要制作的东西有多“安全”。仅仅因为您的参数指定需要协议(protocol)并不意味着传递的实例实现了该协议(protocol)。编译器所需要的只是让您保证在调用(强制转换)时它会这样做。</p>

<p>通常,如果您正在编写所有代码,那么仅使用协议(protocol)而不在运行时检查是相对“安全”的。</p>

<p>如果其他人正在使用代码,特别是如果您将代码作为库或类似的东西发布,那么检查会变得更加谨慎,因为您无法对其他人将要做什么做出任何假设。在这种情况下,最好尽早失败。</p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 当已知对象符合协议(protocol)时,断言对象包含某些方法是一种好的模式吗?,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/21016560/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/21016560/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 当已知对象符合协议(protocol)时,断言对象包含某些方法是一种好的模式吗?