Difference bewteen declaring a NSString with alloc and init and assigning with @“myString”

Currently I’m troubled with a small understanding issue on Objective-C. As example following Aaron Hillegass’s book, I’m wondering about assigning an NSString in the init method of a class a value like in this example (For people who know the book, this is used in the Person class of RaiseMan):

- (id)init
   if(![super init])
     return nil;
   myString = @"New entry";
   return self;

This string isn’t allocated by me, so normally I shouldn’t bother about releasing it.

  • How to debug memory leaks when Leaks instrument does not show them?
  • NSJSONSerialization and Emoji
  • Objective C Array and Object Release
  • localizedCaseInsensitiveContainsString not available in Swift
  • Find and replace long words in an NSString?
  • Why is @autoreleasepool still needed with ARC?
  • BUT! What happens in a setter-method of this string? Following the memory management rules the method should look like:

    - (void)setMyString:(NSString *)newString
        if(myString != newString) {
            [myString release];
            [newString retain];
            myString = newString;

    Why does [myString release] work? I’ve read somewhere, that with = @"bla" assigned strings can’t be released.

    And is initializing with = @"bla" the right way? Or should I use alloc and init instead?

    Thanks for any help 🙂

    3 Solutions Collect From Internet About “Difference bewteen declaring a NSString with alloc and init and assigning with @“myString””

    NSString *constantString = @"constantString";

    String like constantString are said to be from a private(?) class NSConstantString and they are alive through all your program life. Off-course release and retain work, (in the mean that they won’t give you a exception or crash) They just do nothing.

    Read more here

    Also you said in one of your comments that it would be a{@property(..., copy) NSString myString;But what you are showing us is a typical @property(..., retain)

    AFAIK, string constants of the form @”…” are actually a child class of NSString that redefine retain and release as no-ops. This allows the compiler to store those string constants in the data segment of your executable instead of on the heap.

    Is myString declared in the header-file? Like: @property(nonatomic, retain) NSString myString. If that is the case, then myString is retained. Otherwise, it’s not necessary to release it.