Who Owns This Object?

Discussion in 'Mac Programming' started by shusseina, Mar 26, 2009.

  1. macrumors newbie

    Joined:
    Feb 23, 2009
    #1
    If method1 has the following line of code, does method1 then own the object (and therefore need to release it)?

    Code:
    NSString *EOL = @"\n";
    If the above code is legal, why would anyone use either of these two alternatives?

    Code:
    NSString *EOL;
    EOL = [[NSString alloc] init];
    EOL = @"\n";
    or

    Code:
    NSString *EOL;
    EOL = [NSString stringWithString:@"\n"];
    Thanks
     
  2. macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #2
    NSString literals live forever. No one needs to release or autorelease them.

    They would not, as assigning the string literal changes the address, so you're leaking memory because you no longer have a pointer to the Object created in the second line.

    It seems unlikely that someone would do this... but obviously the method is there, so you can do it. You have the power to control the lifetime of EOL now, but you still have the NSString literal that will live forever, so the benefits are negligible.

    -Lee
     

Share This Page