【在UIViewController的init方法中对self.view进行设置需要谨慎】
今天在项目中用到了一个UIViewController的子类,重写了其初始化方法,并在初始化方法中通过self.view setFrame:方法对其大小进行了修改。结果界面上的内容都没有了,纠结了半天才恍然大悟,血的教训啊!!!
事情是这样子的:
以下是纯记事本写的代码,伪码算是。
@interface ViewControllerA:UIViewController
{
}
@property(nonamic,retain)ClassB * classB;
@implementation ViewControllerA
@sythesize classB;
-(id)initWithAClassB:(ClassB *)b //假如传进来的b的value属性=10;
{
if(self = [super init])
{
[self.view setFrame:CGRectMake(0,0,100,100)];
self.classB = b;
//调用其他方法
NSLog(@"when init b.value = %d",self.classB.value);
}
return self;
}
-(void)viewDidLoad
{
[super viewDidLoad];
[self addSubViews];
//调用其他方法
NSLog(@"when didload b.value = %d",self.classB.value);
//此处调用的方法用到了self.classB.value值,但是每次运行都发现传进来的值并不是10,而是默认的0
}
-(void)addSubViews
{
//代码块
NSLog(@"when addSubViews b.value = %d",self.classB.value);
}
结果输出了:
when addSubViews b.value = 0
when didload b.value = 0
when init b.value = 0
===================================================================
我就纳闷儿了,明明是先init再didload的呀,为什么输出顺序是这样子的呢?
后来好好仔细检查了一遍代码,发现在self.classB = b;赋值之前调用了self.view,这个时候self.view还没有,所以要去先加载view,所以导致了这种情况。以前瞎写,完全没有注意到有这个问题,今天涨姿势了。。。