5

I know that Java and C# both use a string pool to save memory when dealing with string literals.

Does Objective-C use any such mechanism? If not, why not?

Community
  • 1
  • 1
Barjavel
  • 1,626
  • 3
  • 19
  • 31

1 Answers1

6

Yes, string literals like @"Hello world" are never released and they point to the same memory which means that pointer comparison is true.

NSString *str1 = @"Hello world";
NSString *str2 = @"Hello world";
if (str1 == str2) // Is true.

It also means that a weak string pointer won't change to nil (which happens for normal objects) since the string literal never gets released.

__weak NSString *str = @"Hello world";
if (str == nil) // This is false, the str still points to the string literal
David Rönnqvist
  • 56,267
  • 18
  • 167
  • 205