Sometimes when I program for the iPhone, I wonder when you have to allocate and initialize objects and when not to. When you are using UI controls, it seems as if you don’t have to do so. Is this true and why?
(Assume that they have been declared in the .h of the view controller.)
Example:
label1.text = @"Hello";
vs
label1 = [[UILabel alloc] init];
label1.text = @"Hello";
Is this because I’m using Interface Builder? Would I have to do this if I were to write our my GUI in code?
Your confusion is because of the NIB file – a NIB file is basically a frozen object graph (i.e. a object with children, who has other children, etc). When you load that NIB file, the runtime calls all of the allocs and inits for you, so that they’re already created.
When you want to create an object that hasn’t been previously specified in the NIB file, that’s when you need alloc/init.