4

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,597
  • 3
  • 18
  • 31

1 Answers1

5

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
  • 55,638
  • 18
  • 162
  • 201