Confused about alloc and release
I'm a little confused about Objective-C and allocating/releasing objects.
If I do this:
NSString *myString;开发者_运维知识库
if([someString isEqualToString: @"test1"]){
myString = @"got 1";
}else{
myString = @"got 2";
}
Do I have to release myString
after that?
And the same with self-defined objects:
myOwnObject *someObject = [someArray objectAtIndex: 1];
myButton.label1.text = someObject.name;
Do I have to release someObject
?
The reason why I'm asking is that I get memory-leaks in a method and I can't find where it is. So I'm trying to figure out whether I do the alloc/release stuff correctly. The leak occurs on a NSPlaceholderString (I guess that's somewhere hidden in my NIB-File).
Also - if I have an object, allocate it, but only use some of the properties, but DO a release of every property on dealloc - will this cause memory leaks?
Sorry - hope my questions do make at least some sense :)
Thanks for any help!
Listen to me. THIS IS THE ONLY RULE THAT MATTERS.
If you use a method with "copy", "alloc", "new", or "retain" in the name
You own the object and MUST later release or autorelease it.
If you don't:
Don't!
But don't expect the object to stick around outside of that scope, because you don't own it.
It's that simple.
MyClass *foo = [[MyClass alloc] init];
[array addObject:foo];
[foo release];
Did you use "copy", "retain", "new", or "alloc"? Yes. Release it.
MyClass *someObject = [someArray objectAtIndex:0];
Did you use "copy", "retain", "new", or "alloc"? No. Don't release it.
BUT
If you have an instance variable which you need to access in other methods:
ivar = [[someArray objectAtIndex:0] retain];
Then you're guaranteed it will stick around because you own it.
(Another way to handle this is with @property (retain)
properties, because then you can do self.ivar = someObject
and it'll retain it for you.)
But remember to release them in -dealloc
!
No, you don't have to release either of those. I usually release
only objects that I alloc
, such as this snippet:
NSString *string = [[NSString alloc] initWithFormat:@"%@", something];
// yadda yadda yadda some code...
[string release];
To answer your first question, you don't need to release strings created with the @"" syntax.
On your second example, you should not have to release someObject
. However, a problem could arise if your dealloc
method in your myOwnObject
class does not correctly release all of its instance variables.
精彩评论