What does assigning a literal string to an NSString with “=” actually do?

前端 未结 3 1034
我在风中等你
我在风中等你 2020-12-20 17:17

What does the following line actually do?

string = @\"Some text\";

Assuming that \"string\" is declared thusly in the header:



        
3条回答
  •  感动是毒
    2020-12-20 17:24

    The assignment is just that. The string pointer is basically a label that points to specific address in memory. Reassignment statement would point that label to another address in memory!

    It doesn't change reference counting or do anything beyond that in Objective-C. You need to maintain the reference count yourself, if you are running in a non-garbage-collection environment:

    [string release];
    string = [@"Some text" retain];
    

    However, string literals don't need to be managed, as they get allocated statically and never get deallocated! So the release and retain methods are just NOOPs (i.e. no operations). You can safely omit them.

提交回复
热议问题