爲什麼UIButton不需要分配和初始化調用,而我們只使用 UIButton *myBtn = [UIButton buttonWithType:UIButtonTypeCustom];
。爲什麼UIButton不需要alloc和init?
- 上述行是否自動分配s並初始化uibutton?
- 是否需要釋放myBtn ?,因爲我沒有明確地使用alloc和init。
這可能是一個簡單的問題,但我不知道這個問題的正確答案,有沒有人可以幫忙?任何幫助表示讚賞,在此先感謝。
爲什麼UIButton不需要分配和初始化調用,而我們只使用 UIButton *myBtn = [UIButton buttonWithType:UIButtonTypeCustom];
。爲什麼UIButton不需要alloc和init?
這可能是一個簡單的問題,但我不知道這個問題的正確答案,有沒有人可以幫忙?任何幫助表示讚賞,在此先感謝。
有一組規則,該方法名稱遵循 - read this link)
基本上,名稱以alloc
,new
,copy
或mutableCopy
開始需要向release
(或autorelease
)。
任何其他返回對象的方法都會返回自動釋放對象。
例如:
// You need to release these
NSString *myString = [[NSString alloc] init];
NSString *nextString = [myString copy];
UIbutton *button = [[UIButton alloc] initWithType:UIButtonTypeCustom];
// You don't need to release these
NSString *thirdString = [NSString stringWithString:@"Hello"];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
希望幫助!
那麼buttonWithType將返回一個類型的UIButton,這是你的alloc
和init
。它也是autoreleased。
你可以als alloc
和init
一個UIButton你自己,這會給你一個類型爲UIButtonTypeCustom
的UIButton。
這不一定意味着自定義按鈕。但是,自動釋放+1。 –
buttonWithType
返回一個自動釋放的對象,您不必釋放它。由於您沒有alloc
,因此無需release
。
對於每個UIClass對象都隱藏實現類級別的alloc方法來自NSObject在UIButton的情況下我們也得到alloc方法如果我們寫了但是蘋果Guy給了一個更多的方法叫做buttonwithtype class level方法,這樣
(id)buttonWithType:(UIButtonType)buttonType
{
UIButton=[NSObject alloc];
code for button type specification
return id;
}
這就是爲什麼我們不用做頁頭再次
非常感謝你的建議deanWombourne,這真的很有幫助 – George