ios - Objective-C 类的通用初始化程序

标签 ios objective-c macos cocoa

多年来我一直在使用 Objective-C 进行编程,我总是遇到这个问题:如果你有一个具有多个初始化器的对象,但所有这些都有共同的代码,你如何将它提取出来?

我能想到的最好的是这样的:

@implementation Example

- (void)privateInitWithString:(NSString*)aString
{
  self.str = aString;
}

- (id)init
{
  self = [super initWithWindowNibName:@"MyNib"]
  if(self) {
    [self privateInitWithString:@""];
  }
  return self;
}

- (id)initWithString:(NSString*)aString
{
  self = [super initWithWindowNibName:@"MyNib"]
  if(self) {
    [self privateInitWithString:aString];
  }
  return self;
}

@end

各个初始化程序中有很多重复的代码味道。但是我想不出一种方法让一个初始化程序“失败”到另一个初始化程序,因为不能保证在调用 [super init] 之前设置了 self >

是否有我缺少的最佳实践?

最佳答案

你写一个“指定的初始化器”。该初始化程序处理所有不同的情况。在您的情况下, initWithString 似乎是一个不错的选择。而 init 就变成了

- (instancetype)init { return [self initWithString:@""]; }

您可以在这里阅读更多相关信息:

https://developer.apple.com/library/ios/documentation/general/conceptual/CocoaEncyclopedia/Initialization/Initialization.html

关于ios - Objective-C 类的通用初始化程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22075123/

相关文章:

ios - 如何在 Xcode Playground 中实现自定义字体

android - Cordova 应用程序在新应用程序版本中保留本地存储数据吗?

iphone - Objective-C 中的位转换工具

ios - UITableViewStyleGrouped 不起作用

iphone - UIWebView 不加载 URL

macos - Mac 窗口图标化按钮的 Hook

java - 客户端 (X509) 认证的默认环境应该是什么

ios - UITextView 中的文本更改事件

iphone - 如何使用 TWTweetComposeViewController 发送多个 UITextField 推文?

macos - 适用于 Mac 的最佳 F# IDE