NSString *string = @“someString” vs NSString *string = initWithFormat@“%@”, string]

If I have a method

- (void) myMethod:(NSString *)string {
    [Object anothermethodWithString:string];
}

and I call

  • how to add and retrieve data from plist programmatically
  • Search and highlight text in PDF rendered in UIView
  • Add UIView Above All Other Views, Including StatusBar
  • iPhone, sqlite3, how do detect a null date, getting error when assigning to a NSString?
  • XCode Base internationalization doesn't work
  • Writing an app to stream video to iPhone
  • [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.

    2 Solutions Collect From Internet About “NSString *string = @“someString” vs NSString *string = initWithFormat@“%@”, string]”

    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.

    If you use : NSString *str = @””. It is kind of a constant, you don’t need to do any memory management.

    If you call from a method : NSString *str = [NSString stringWithFormat:@””], the str is already autoreleased.

    If you manually alloc, init. You need to call release, or autorelease yourself.

    The general memory convention is : if you do something with new, alloc, retain, or copy, you need to release it yourself, any other cases, the object is autoreleased, don’t release it