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

前端之家收集整理的这篇文章主要介绍了ios – 为什么UIView同时调用init和initWithFrame?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我注意到当我覆盖init和initWithFrame时:在UIView子类中,两个方法都被调用.即使在我的代码中只有一个是显式调用

TestViewController.m:

  1. @implementation TestViewController
  2.  
  3. - (void)viewDidLoad
  4. {
  5. [super viewDidLoad];
  6.  
  7. View1 *view1 = [[View1 alloc] init];
  8. [self.view addSubview:view1];
  9. }
  10.  
  11. @end

View1.m:

  1. @implementation View1
  2.  
  3. - (id)initWithFrame:(CGRect)frame
  4. {
  5. self = [super initWithFrame:frame];
  6. if (self)
  7. {
  8. NSLog(@"initWithFrame");
  9. }
  10. return self;
  11. }
  12.  
  13. - (id)init
  14. {
  15. self = [super init];
  16. if (self)
  17. {
  18. NSLog(@"init");
  19. }
  20. return self;
  21. }
  22.  
  23. @end

控制台看起来像这样:

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

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

为什么在init之前调用initWithFrame?

解决方法

原因是View1中的initWithFrame:你调用[super initWithFrame:].
UIView initWithFrame:调用[self init].

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

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

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

  1. - [view1(View1) init]
  2.  
  3. - [view1(UIView) init] (called by [super init] inside View1)
  4.  
  5. - [view1(View1) initWithFrame:CGRectZero] (called inside [view(UIView) init] )
  6.  
  7. - [view1(UIView) initWithFrame:CGRectZero] (called by [super initWithFrame] inside View1)
  8. - ...
  9.  
  10. - NSLog(@"initWithFrame"); (prints "test1[8422:60b] initWithFrame")
  11.  
  12. - NSLog(@"init"); (called inside [view1(View1) init] ; prints "test1[8422:60b] init")

检查OOP中的继承.

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

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

猜你在找的iOS相关文章