Zhigang An Zhigang An - 1 year ago 110
Objective-C Question

NSString and Objective-C Memory Management ARC

I'm a little confused when coding an Objective-C project. The ARC is on. Here is a sample code:

NSString *foo = [[NSString alloc] initWithUTF8String:"This is a C string."];

// Use foo here...

foo = @"This is an ObjC string."

Here are my questions:

  1. Do I need to explicitly terminate C string with '\0' in
    method, or it is okay to omit NULL terminator?

  2. Is there any memory leakage when I reuse
    as a pointer and assign new Objective-C string to it? Why?

  3. If I change
    to other class, like
    or my own class, is there any difference for question 2? (Initialize an object and then reassign other value directly to it.)

Thank you!

Answer Source
  1. An explicit \0 is not required because in C (and hence Objective C), quoted string literals are null-terminated implicitly by the compiler. Here's a similar question.

Do string literals that end with a null-terminator contain an extra null-terminator?

  1. No memory leakage. The ARC-configured compiler will generate code to release the first string that was being referenced before assigning the new string.

  2. No change. You may get a compile-time warning if the types aren't compatible.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download