If I have a method
- (void) myMethod:(NSString *)string {
[Object anothermethodWithString:string];
}
and I call
[Object myMethod:@"this is a string with no alloc statement"]
Do I need to do something like
- (void) myMethod:(NSString *)string {
NSString *string2 = [[NSString alloc] initWithFormat:@"%@", string];
[Object anothermethodWithString:string2];
[string2 release];
}
instead of the way I had myMethod before? I have misbehaving code that seems to be caused by a string being auto-released while a second method within another method is being called (like in the example). The second way I have myMethod fixed all of my problems.
So is a “non-alloc” string an auto-released string? I asked this question as a follow up to another question (which was completely unrelated and is why I am creating this post), and a few sources said that I don’t need to reallocate the string. I am confused, because the behavior of my code tells me otherwise.
Dave’s got it right. You only need to worry about calling
releaseon objects that younew,alloc,retain, orcopy.The above rule works very well, but if you’re curious and want to get into a lot of detail, I suggest reading the Memory management Programming Guide from Apple’s docs. It’s free and goes from basic concepts into a lot of details.