retain and autorelease questions.
// A
UIView *temp = [[UIView alloc] init];
myView = temp;
[temp release];
// B
myView = [[UIView alloc] init];
Do the two codes have no differences?
NSString *str = [NSString stringWithString:@"Hello"];
NSString *str = @"Hello";
And these two? I'm not sure about retain count yet. Thank you.
For the first example, they are very different. In first code chunk, the UIView given to temp has a retain count of 1 (thanks to alloc
). When you release it on the third line, the MyView variable is now bad, because the object could be destroyed. If you want MyView to keep it, do:
MyView = [temp retain];
The second part of the first example will create an entirely new instance of a UIView, which has no relationship to temp
.
In the second example, the stringWithString
method will autorelease
your string, meaning that it will be automatically released for you when the "release pool" is released, much later. You don't have to worry about releasing it. In the second line, however, the string is statically allocated. Retain counts and releasing are totally unnecessary with them.
Forgot to mention... check out the answer to this question for more about the retain/release rules.