为什么UIView同时调用init和initWithFrame?

Ser*_*gey 8 objective-c uiview ios

我注意到,当我覆盖两个initinitWithFrame:UIView子类中,这两种方法被调用.即使在我的代码中只有一个是显式调用:

TestViewController.m:

@implementation TestViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    View1 *view1 = [[View1 alloc] init];
    [self.view addSubview:view1];
}

@end
Run Code Online (Sandbox Code Playgroud)

View1.m:

@implementation View1

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        NSLog(@"initWithFrame");
    }
    return self;
}

- (id)init
{
    self = [super init];
    if (self)
    {
        NSLog(@"init");
    }
    return self;
}

@end
Run Code Online (Sandbox Code Playgroud)

控制台看起来像这样:

2013-10-17 12:33:46.209 test1 [8422:60b] initWithFrame

2013-10-17 12:33:46.211 test1 [8422:60b] init

为什么在init之前调用initWithFrame?

man*_*jmv 8

这不是问题.在的情况下UIView的一个[super init]电话将自动更改为[super initWithFrame:CGRectZero] .因此,您必须牢记这一点来维护此代码.


mar*_*ros 7

原因是在View1 initWithFrame:你打电话里面[super initWithFrame:]. UIView initWithFrame:电话[self init].

在类中调用方法时,将调用子类上的方法.因此,当您在UIView上调用实例方法(例如init)时,它会尝试在View1上调用init方法(如果已实现).

编辑根据以下答案:https://stackoverflow.com/a/19423494/956811

让view1成为View1的一个实例.
调用层次结构是:

   - [view1(View1) init] 

      - [view1(UIView) init] (called by [super init] inside View1)

        - [view1(View1) initWithFrame:CGRectZero] (called inside [view(UIView) init] )

           - [view1(UIView) initWithFrame:CGRectZero] (called by [super initWithFrame] inside View1) 
              - ...

           - NSLog(@"initWithFrame"); (prints "test1[8422:60b] initWithFrame")

      - NSLog(@"init"); (called inside [view1(View1) init] ; prints "test1[8422:60b] init")
Run Code Online (Sandbox Code Playgroud)

检查OOP中的继承.

http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)

http://www.techotopia.com/index.php/Objective-C_Inheritance