0

I think the result under the second example below should be "null", but after I run the code, I found that in Example 1 the output is "Strong-String" and in Example 2 it's "null"

I really don't understand why this is.

Examples:

// property definition
@property (nonatomic, strong) NSString *strongStr;
@property (nonatomic, weak)   NSString *weakString;

// Sample 1
self.strongStr  = @"Strong-String";
self.weakString = self.strongStr;
self.strongStr  = nil;
// output -> Strong-String
NSLog(@"waekstring = %@", self.weakString);

// Sample 2
self.strongStr  = [[NSString alloc] initWithUTF8String:"Strong-String"];
self.weakString = self.strongStr;
self.strongStr  = nil;
// output -> null
NSLog(@"waekstring = %@", self.weakString);
jscs
  • 63,694
  • 13
  • 151
  • 195
林晖杰
  • 61
  • 10

1 Answers1

1

when you define a string like

// Sample 1
self.strongStr  = @"Strong-String";

the compiler actually keeps a static reference to that string, if you were to create another string with the same characters, you would notice the memory address of both the strings would be the same. The compiler does this to help save memory when the same string is used over and over so it doesnt have to reallocated the memory every time. this is why the string does not get deallocated, while the manually alloc/inited one does

Fonix
  • 11,447
  • 3
  • 45
  • 74