Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSString *string = @"someString" vs NSString *string = [[NSString alloc] initWithFormat@"%@", string]

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.

like image 916
Ayaka Nonaka Avatar asked Sep 11 '26 12:09

Ayaka Nonaka


1 Answers

Dave's got it right. You only need to worry about calling release on objects that you new, alloc, retain, or copy.

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.

like image 185
Neal L Avatar answered Sep 14 '26 03:09

Neal L



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!