如果一个类没有文档指定的初始化程序怎么办?

tec*_*Mex 9 cocoa-touch objective-c ios

我正在寻找有关如何处理这种情况的一般指导.这是一个具体的例子.

我是UIImageView的子类,我希望覆盖initWithImage以在使用提供的图像使用超类init本身之后添加我自己的初始化代码.

但是,UIImageView没有文档指定的初始化程序,所以我应该调用哪个超类初始化程序以确保我的子类正确初始化?

如果某个类没有指定初始值设定项,请执行以下操作:

  1. 假设调用任何类(UIImageView)初始值设定项是安全的?
  2. 查看超类(UIView)指定的初始化程序?

在这种情况下,似乎#1将是答案,因为在我的重写初始化程序中执行以下操作是有意义的:

- (id)initWithImage:(UIImage *)image
{
    self = [super initWithImage:image];
    if (self) {
        // DO MY EXTRA INITIALIZATION HERE
    }
    return self;
}
Run Code Online (Sandbox Code Playgroud)

Dar*_*ren 5

UIImageView有两个初始值设定项,因此您可能希望确保子类处理这两个初始化路径.

您可以简单地声明这-initWithImage:指定的初始化程序,并且不支持所有其他初始值设定项.

此外,您可以实现-initWithImage:highlightedImage:并抛出异常以指示它不受支持.

或者,您可以声明-initWithImage:highlightedImage:为指定的初始化程序,并且可以-initWithImage:调用指定的初始化程序.

或者,您可能会发现-initWithImage:无论您的类是否使用-initWithImage:或初始化,都会调用初始值设定项-initWithImage:highlightedImage:.

  • @HotLicks,您需要在Apple的文档中搜索术语"指定的初始化程序".这不是一些弥补的术语.这是[Cocoa中的一个重要概念](https://developer.apple.com/library/ios/documentation/general/conceptual/CocoaEncyclopedia/Initialization/Initialization.html#//apple_ref/doc/uid/TP40010810-CH6-SW3 ). (2认同)