What's the difference between the following two code snippets?
1.
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = frame;
2.
UIButton *button = [[[UIButton alloc] initWithFrame:frame] autorelease];
I think they're equivalent. Haha! Trick question you sneaky little punk!
Reasoning
-buttonWithType:returns an autoreleasedUIButtonobject.
+[NSObject alloc]defaults scalar instance variables to0, sobuttonTypeshould be0, orUIButtonTypeCustom.Pros & Cons
You could argue that it's clearer to use
-buttonWithType:and setbuttonTypeexplicitly and that it's safer in case Apple changesUIButtonTypeCustomto be1instead of0(which will most certainly never happen).On the other hand, you could also argue that it's clear & safe enough to use
-initWithFrame. Plus, many of the Xcode sample projects, such as "TheElements" & "BubbleLevel," use this approach. One advantage is that you can explicitly release theUIButtonbefore the run loop for your application's main thread has drained its autorelease pool. And, that's why I prefer option 2.I would strongly suggest using the first approach (
+buttonWithType), because that's the only way to specify the button type.If you
+allocand-initWithFrame:, thebuttonTypeis set to some standard value (not sure which, and this could change in later versions of the SDK) and you can't change the type afterwards because thebuttonTypeproperty is read only.
1759

被折叠的 条评论
为什么被折叠?



