Reputation: 417
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.
Upvotes: 1
Views: 851
Reputation: 17314
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.
Upvotes: 3
Reputation: 6683
One useful thing, is that you can NSLog the retaincount, so that you can do testing on your own.
But back to your question...
IF MyView is a property, and you had referenced it with self.MyView and it was declared with retain or copy, your 2 statements are the same. If MyView is just a local variable, your UIView will dealloc when you do
[temp release];
because you have done nothing to increase the retain count since you alloced it.
For your string example...
[NSString stringWithString:@"Hello"];
returns an autoreleased string. if you will need to keep it for a very long time, you'll want to put a retain on it.
The second string example is a statically allocated string, and you do not have to worry about it. retain counts don't apply to them.
Upvotes: 0
Reputation: 674
Remember that the reference MyView just points to temp. So as soon as you release temp, this also affects MyView.
The [NSString stringWithString:] is mainly used for copying other strings instead of referring to the memory address. E.g:
A:
NSString *string = someOtherString; // Copies the reference to someOtherString;
B:
NSString *string = [NSString stringWithString: someOtherString]; // Makes a copy of the other string.
Upvotes: 0
Reputation: 35384
First part: It's not the same!
MyView will be released too, because you're just copying the pointer (retain count 0). In the second code MyView will have retain count of 1.
Second part: It's basically the same.
Upvotes: 0