【问题标题】:In Objective-c what I should use to return that parameter can't be nil?在Objective-c中,我应该使用什么来返回该参数不能为零?
【发布时间】:2014-04-30 11:13:19
【问题描述】:

我知道我可以通过 NSError 或抛出 NSException 返回该参数不能为 nil,但是在 Objective-c 中通知该参数不能为 nil 的最佳选择是什么?

【问题讨论】:

    标签: ios objective-c null nserror nsexception


    【解决方案1】:

    文档。

    在开发过程中使用断言引发异常。

    也返回一个NSError(尽管希望在您投入生产时它永远不会发生)。

    【讨论】:

      【解决方案2】:

      您可以使用NSAssert(),它只会在未定义NS_BLOCK_ASSERTIONS 的构建中触发:

      - (void)someMethodWithParam:(id)someParam {
          NSAssert(someParam, @"someParam cannot be nil");
          ...
      }
      

      这将几乎限制您和其他开发人员进行检查,但如果您希望它持续存在,无论构建如何,那么NSException 是最好的:

      - (void)someMethodWithParam:(id)someParam {
          if (!someParam) {
              [NSException raise:@"MyException" format:@"someParam cannot be nil"];
          }
          ...
      }
      

      【讨论】:

      • NSParameterAssert 在这里更合适
      【解决方案3】:

      在编译时检查使用

      __attribute__ with nonnull
      

      例如,第一个和第二个参数不能为空:

      extern void * my_memcpy (void *dest, const void *src, size_t len) 
      __attribute__((nonnull (1, 2)));
      

      nonnull 属性指定某些函数参数应该 是非空指针。使用非空编码对值的期望 进入明确的合同,这可以帮助捕获任何 NULL 指针错误 潜伏在任何调用代码中。记住:编译时错误≫运行时 错误。

      阅读更多here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-06-20
        • 2019-09-18
        • 1970-01-01
        • 1970-01-01
        • 2011-11-07
        • 2012-02-26
        • 1970-01-01
        相关资源
        最近更新 更多