0

these code will get a warning: assigning retained object to weak variable object will be released after assignment

__weak NSString *str = [[NSString alloc] initWithFormat:@"1234"];
NSLog(@"url:%@",str);

but the nslog will print 1234 normally,seems that the object isn't released after assignment , so when will the release happend?

ximmyxiao
  • 2,622
  • 3
  • 20
  • 35

1 Answers1

2

You can get the behavior you expect by setting OBJC_DISABLE_TAGGED_POINTERS to YES in the program's environment. For example, you can set it in your scheme in Xcode like this:

setting environment variable in scheme

What's going on (if you don't set that environment variable) is the Objective-C runtime supports tagged pointer strings. This means that short strings of common characters are encoded entirely in the 64-bit object reference, stored in the str variable. There is no heap allocation. Since there is no heap allocation for the string, and since the string cannot itself have references to other objects, the runtime knows it doesn't actually need to arrange for the __weak variable to be set to nil, so it doesn't.

By setting that environment variable, you disable the use of all tagged pointers, including tagged pointer strings. So I wouldn't recommend it for production code.

You can read more about tagged pointer strings in this excellent article by Mike Ash.

rob mayoff
  • 375,296
  • 67
  • 796
  • 848
  • thanks @rob now i understand it, and i want to know why the retain object be released immediately when assigned to weak object , any document on this ? – ximmyxiao Dec 20 '16 at 03:43
  • Check out http://stackoverflow.com/a/9747451/77567 or http://stackoverflow.com/a/36783748/77567 – rob mayoff Dec 20 '16 at 18:14
  • Note that if the string is static (e.g.: @"xyz") it may be located in the __const section and so retain/release operations on it are no-ops just like tagged pointers. – russbishop Jun 28 '17 at 06:26