1. 为什在addsubview对象后,要release它

在section 2.4例子中上看到 

--loadview

{

.....

[contentView addSubview:label];

 

[label release]; // 这是因为addsubview这个方法是使用retain的方式,为了避免内存泄露所以需要release.具体见下面addsubview的介绍。

 



self.view = contentView;

[contentView release]; //之所以这样做是因为在viewconttroller中的view是retain特性,“ @property(nonatomic,retain) UIView *view;

}

2. 在实现 [viewA  addSubview ViewB]会invoke viewB的loadview方法的解释。 

HelloWorldViewController *hwvc; hwvc = [[HelloWorldViewController alloc] init];

 

[window addSubview:hwvc.view]; //会invoke hwvc的loadview方法,这是因为在hwvc.view这个时候还是nil,因此就会自动的call hwvc的loadview方法。换句话说如果hwvc.view已经被有value了就不会call到loadview, 如下面的例子所示

 

 

 

-(void)applicationDidFinishLaunching:(UIApplication *)application

{

UIWindow *win = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

HelloWorldViewController *winctrl = [[HelloWorldViewController alloc] init];

#if 1

NSLog(@"create view to avoid calling loadview method");

UIView *contentView =[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];

    winctrl.view = contentView;

[contentView release];

#endif

[win addSubview: winctrl.view]; // the loadview method will not be called.

[win makeKeyAndVisible];

} 

  

 

addSubview:

Adds a view to the end of the receiver’s list of subviews.

- (void)addSubview:(UIView *)view
Parameters
view

The view to be added. This view is retained by the receiver. After being added, this view appears on top of any other subviews.

 

 loadView 

Creates the view that the controller manages.

- (void)loadView
Discussion

You should never call this method directly. The view controller calls this method when the viewproperty is requested but is currently nil.