0

The following code is not doing what I expect.

We have a strong string and a weak string. My understanding of ARC is that when there are no references to a weak variable it will be deallocated, however, the last line the weak string still has a value.

// Make a strong and weak variable
__strong NSString *strongString = @"Moo";
__weak NSString *weakString = nil;
weakString = strongString;

NSLog(@"weak: `%@` \t strong: `%@`", weakString, strongString);
// As expected this prints,
// weak: `Moo`   strong: `Moo`


// Now set the weak reference to nil
weakString = nil;
NSLog(@"weak: `%@` \t strong: `%@`", weakString, strongString);
// As expected this prints,
// weak: `(null)`    strong: `Moo`

// Now reset the weak variable and set the strong variable to nil
weakString = strongString;
strongString = nil;
NSLog(@"weak: `%@` \t strong: `%@`", weakString, strongString);
// Unexpectedly this prints,
// weak: `Moo`   strong: `(null)`
// I was expecting to see weak: `(null)`     strong: `(null)`

Unless I have misunderstood, it looks like the weak variable has become strong.

Daniel Farrell
  • 9,316
  • 8
  • 39
  • 62
  • No, the solution to this question is different. Here the problem was NSString specific see the answer below. – Daniel Farrell Jul 11 '14 at 13:43
  • you question is not different at all, the referred topic is exactly about `NSString` object, but the answer is more generic, it does not focus on only `NSString` objects. – holex Jul 11 '14 at 13:51
  • OK I'll check that out more closely. ... Yes, http://stackoverflow.com/questions/10922888/strong-and-weak-for-local-variable-i-dont-understand provides a nice answer, the other one is not so good. – Daniel Farrell Jul 11 '14 at 13:52

1 Answers1

1

This happens because the when you create a string in the form @"some string", the compiler creates what is called NSCFConstantString, which has an infinite reference count, so it can never deallocate. It's an optimization to keep such constant strings in memory. Try this with any other class (or NSString that was created by alloc/init), and all should work as expected

Kaan Dedeoglu
  • 14,765
  • 5
  • 40
  • 41
  • NSString are probably a bad example. I changed the code to use NSNumber instead. Yes, when creating an object with alloc/init this behaves as expected. I noticed that if I use an autoreleasing method to create the a number like -numberWithDouble: the same behaviour occurs? – Daniel Farrell Jul 11 '14 at 13:49