我有一個方法,需要一個UIButton,修改它的屬性並返回一個UIButton。但是,它似乎沒有被初始化。我確信我在這裏做了內存管理方面的錯誤,但並不知道如何解決這個問題。沒有發生運行時錯誤。在方法中返回自定義的UIButton?
它被稱爲是這樣的...
newGameBtn = [self customButtonFromButton:newGameBtn
withText:[NSString stringWithFormat:@"NEW GAME"]
withFontSize:22
withBorderColor:[UIColor orangeColor]
isSilent:YES];
[dashboardContainer addSubview:newGameBtn];
的方法定義如下......
- (UIButton*) customButtonFromButton:(UIButton*)button withText:(NSString*)text withFontSize:(int)fontSize withBorderColor:(UIColor*)borderColor isSilent:(BOOL)isSilent {
button = [[[UIButton alloc] init] autorelease];
// Set properties from parameters
// Other conditional custom stuff here
return button;
}
注:newGameBtn
是類型的UIButton的*,並與初始化: newGameBtn = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
另一個選擇可能是子類UIButton,但我想我會嘗試解決這個問題,因爲我已經走過了這條路。
+1。工廠方法是獲得正確配置的按鈕的*唯一*方法。使用任何init方法都依賴於當前可能會隨時改變的實現。沒辦法設置按鈕類型,例如 - 這是一個重要的屬性。這就是爲什麼子類化也不合適的原因。 – Eiko
啊,在重構中,我忘了移動被摧毀的框架。是的。那樣做了。請注意,在我對@Martin Ullrich的回覆中,我實際上是在使用buttonWithType:init。 –