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

人走茶凉 提交于 2019-12-20 04:51:10

问题


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.

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 :)


回答1:


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)




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/4804943/difference-bewteen-declaring-a-nsstring-with-alloc-and-init-and-assigning-with

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!