【问题标题】:Better solution to handle required method of a protocol not implemented处理未实现协议所需方法的更好解决方案
【发布时间】:2014-11-22 20:20:21
【问题描述】:

当一个协议所需的方法没有实现时,Xcode 只是给出一个警告

Warning: method 'xxx' in protocol 'xxx' not implemented

我有一个自定义视图,例如 UITableView,他有一个 dataSource 属性。为了确保 dataSource 不是 nil 并且响应我这样做的方法

NSAssert(self.dataSource != nil, @"menu's dataSource shouldn't be nil");
if ([self.dataSource respondsToSelector:@selector(menu:numberOfRowsInColumn:)]) {
    return [self.dataSource menu:self
            numberOfRowsInColumn:self.currentSelectedMenudIndex];
} else {
    NSAssert(0 == 1, @"required method of dataSource protocol should be implemented");
    return 0;
}

我想知道是否有更优雅的方法来处理所需方法的缺失?

有什么想法吗?

【问题讨论】:

    标签: ios objective-c exception-handling datasource protocols


    【解决方案1】:

    该解决方案对我来说看起来不错,因为可以为生产代码禁用断言,使其成为仅限开发人员的健全性检查。

    如果协议可以由第三方代码(即某种插件)实现,则应该引发异常。

    然而,稍微更容易编码和理解的断言将是:

    NSAssert(NO, @"blah blah blah");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-05
      • 1970-01-01
      相关资源
      最近更新 更多