关于awakeFromNib的学习

本文介绍了iOS开发中nib文件的加载过程及其与awakeFromNib方法的关系。nib加载时,首先分配并初始化所有对象,然后连接各对象的外引(outlets)和动作(actions)。初始化器中无法访问外引,因为此时它们尚未被设置。awakeFromNib方法会在所有外引和动作连接完成后被调用,是设置默认值和进行配置的理想时机。

转自:http://blog.youkuaiyun.com/wangyangkobe/article/details/18996227

When a nib is loaded, the nib loader allocates and initializes all objects, then hooks up all of their outlets and actions. Because of the order in which this happens, you cannot access outlets in your initializer. You can try, but they will all be nil.


After all outlets and actions are connected, the nib loader sends awakeFromNib to every object in the nib. This is where you can access outlets to set up default values or do configuration in code. Example:

试译:当所有的“外引”和动作都连接完毕后,nib“加载器”就像nib文件上所有的对象(如button、view)发送awakeFromNib消息。

http://wiresareobsolete.com/wordpress/2010/03/awakefromnib/

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. @implementation SecondView  
  2.   
  3. - (id)initWithFrame:(CGRect)frame  
  4. {  
  5.     self = [super initWithFrame:frame];  
  6.     if (self) {  
  7.         // Initialization code  
  8.     }  
  9.     return self;  
  10. }  
  11.   
  12. - (void)awakeFromNib{  
  13.     [super awakeFromNib];  
  14.     NSLog(@"call %s", __FUNCTION__);  
  15.     self.backgroundColor = [UIColor redColor];  
  16. }  

一般在UIView的子类重载该方法。


[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. @implementation BlueButton  
  2.   
  3. - (id)initWithFrame:(CGRect)frame  
  4. {  
  5.     self = [super initWithFrame:frame];  
  6.     if (self) {  
  7.         // Initialization code  
  8.     }  
  9.     return self;  
  10. }  
  11. - (void)awakeFromNib{  
  12.     [super awakeFromNib];  
  13.     NSLog(@"call %s", __FUNCTION__);  
  14.     self.backgroundColor = [UIColor blueColor];  
  15.     [self setTitle:@"Blue Button" forState:UIControlStateNormal];  
  16. }  
  17. - (id)initWithCoder:(NSCoder *)aDecoder{  
  18.     NSLog(@"call %@"@"initWithCoder");  
  19.     if (self = [super initWithCoder:aDecoder]) {  
  20.         self.titleLabel.text = @"initWithCoder";  
  21.     }  
  22.     return  self;  
  23. }  
  24. @end  

如果是从nib中加载BuleButton,方法 initWithCoder  会调用,并且先于  awakeFromNib  调用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值