iOS 为 initWithNibName 生成的函数结构

标签 ios cocoa-touch

我经常使用 initWithNibName 函数来初始化我的 View Controller 中的内容。我只是注意到生成的 initWithNibName 函数对 self 进行了 nil 检查。

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
  self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
  if(self) {
    //do some initializing
  }
  return self;
}

为什么对 self 进行 nil 检查,如果不是 nil 则运行初始化代码?这个 if-statement 会是假的吗?为什么苹果坚持要我在这里做一个零检查?

最佳答案

简单地说,如果由于“任何”原因而导致您的 Nib 未加载时出现任何情况,则不会有任何初始化 Controller 的感觉,因此

a self.backgroundcolor = [UIColor blackColor];只有当 self 不是 'nil' 时才会执行。

否则,该方法将只返回'nil'

关于iOS 为 initWithNibName 生成的函数结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6986132/

相关文章:

objective-c - MainWindow.xib 和 ViewController.xib

swift - 如何在嵌套循环中访问变量?

iPhone 如何保存 View 状态

ios - 向 Nib 启动的 View 添加边框和阴影

ios - 在 iOS 中顺时针绘制圆弧会导致逆时针圆弧

ios - 如何在同一 View 中重新加载 iPhone 中 UITableView 中的数据

ios - 分配 : *** error for object: Invalid pointer dequeued from free list *** set a breakpoint in malloc_error_break to debug in Magical record IOS

iphone - UIActionSheet 按钮未加载新 View

ios - UICollectionView 中的缩放 ImageView 不一致

iphone - EventKit eventsMatchingPredicate 搜索是否从重复事件中拾取单个实例?