开发者

Do I need to release a constant NSString?

开发者 https://www.devze.com 2023-02-28 21:57 出处:网络
I\'m reading memory management rules to this point where it said - (void)printHello { NSString *string;

I'm reading memory management rules to this point where it said

- (void)printHello {

    NSString *string;

    string = [[NSString alloc] initWithString:@"Hello"];

    NSLog(@"%@", string);

    [string release];

}

you h开发者_开发问答ave ownership and have to release string, but I'm curious about the @"Hello". @" " is the syntax for creating and NSString, and it's an object. So doesn't that get leaked?


@"…" is a literal instance of NSString. When the compiler sees a literal string, it maps the string into the binary file (e.g. your program) and the string is available as an NSString object when the binary is loaded (e.g. when you run your program). You don’t have to manage the memory occupied by literal strings because they’re an intrinsic part of your binary — they are always available, they never get released, and you don’t have to worry about managing their memory.


Bavarious's answer is correct. For the curious, I can add that this is documented in Apple's “String Programming Guide”, specifically the section “Creating Strings” where it says (emphasis mine):

The simplest way to create a string object in source code is to use the Objective-C @"..." construct:

NSString *temp = @"/tmp/scratch";

Note that, when creating a string constant in this fashion, you should use UTF-8 characters. Such an object is created at compile time and exists throughout your program’s execution. The compiler makes such object constants unique on a per-module basis, and they’re never deallocated.

0

精彩评论

暂无评论...
验证码 换一张
取 消