addSubView需要注意的幾個點


 

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.

:view參數代表被增加的view,這個view會被它的接收者retain一次(即引用計數+1)。增加完成之後,這個view將出現在接收者的其他子視圖的上面。

ps:關於子視圖的出現的層次的問題,可以從這些子視圖被保存的數據結構來探尋答案 ,每個視圖都有個數組的屬性,subviews,這個就是保存的它的子視圖的引用。而這個數組的順序就是代表了各個子視圖被加入時的順序。index=0的就是最先被加入進去的,以此類推。所以,索引值越高的視圖越不容易被覆蓋。


Discussion

This method retains view and sets its next responder to the receiver, which is its new superview.

這個方法會retain一次view,並且設置它的下一個響應者是receiver,即它的新的父視圖。

ps:在removeFromSuperview裏已經說過,其實視圖直接的操作往往牽涉到兩個方面的操作,一個是視圖的數據結構,一個是響應者鏈。當然,addsubview也不例外。


Views can have only one superview. If view already has a superview and that view is not the receiver, this method removes the previous superview before making the receiver its new superview.

:每一個視圖只能有唯一的一個父視圖。如果當前操作視圖已經有另外的一個父視圖,則addsubview的操作會把它先從上一個父視圖中移除(包括響應者鏈),再加到新的父視圖上面。


Availability

  • Available in iOS 2.0 and later.

See Also

    • – insertSubview:atIndex:
    • – insertSubview:aboveSubview:
    • – insertSubview:belowSubview:
    • – exchangeSubviewAtIndex:withSubviewAtIndex:

 

 

addSubview和insertSubview的區別

addSubview 是將view加到所有層的最頂層

相當於將insertSubview的atIndex參數設置成view.subviews count

[view addSubview:oneview] == [view insertSubview:oneview atIndex:view.subviews count]

 

addSubview是加到最後
insertSubview是加到指定的位置

 

爲什麼要在addsubview:一個view對象後,release它?

 

先看代碼:

1
2
3
IMGView *imgView = [[IMGView alloc] initWithFrame:CGRectMake(10, 0, 300, 300)];
[self.view addSubview:imgView];
[imgView release];

爲什麼imgView要release呢?可能很多人跟我一樣,之前不是很清楚。 我們逐行分析一下

第一行,alloc一次,imgView對象retainCount爲1,
第二行,addSubview一次,此方法會把你傳過去的對象retain一次,那麼此時它的retainCount爲2。self.view變爲它的第二個待有者。參考:The receiver retains view. If you use removeFromSuperview to remove view from the view hierarchy, view is released.
第三行,調用release方法,此處釋放對imgView的所有權,retainCount減1。

到語言句尾imgView的所有者只剩下self.view,並且它的retainCount僅爲1。內存管理第一鐵則,誰retain(alloc,copy)誰release(autorelease)。上述的做法也是爲了符合這一準則。


發佈了62 篇原創文章 · 獲贊 2 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章