ios - ObjectiveC: Strange behavior when using NSString and __weak with ARC -


first code , output:

nsstring *text = @"sunny"; __weak nsstring *string0 = text.lowercasestring; __weak nsstring *string1; string1 = text.lowercasestring;  nslog(@"%@, %@", string0, string1); 

output:

(null), sunny 

but after move declaration of string1 above text, output different. here code:

__weak nsstring *string1; nsstring *text = @"sunny"; __weak nsstring *string0 = text.lowercasestring; string1 = text.lowercasestring;  nslog(@"%@, %@", string0, string1); 

output:

sunny, sunny 

i confused different output:

  • why string0 , string1 different in first case?
  • why output of second case different first?

trying figure out when object released or weak reference nulled can challenging, , doesn't understanding. here reasons why can see different results expect:

  • nsstring: best never use type when doing these kind of investigations. string literals immortal, not collected, , may have string literal when don't expect one.
  • the auto-release pool: auto-release pool hangover pre-arc days, still exists , many methods return auto-released objects. means many objects live longer might expect, not long. arc has tricks , can remove objects auto-release pool early, might first think object live longer , doesn't...
  • weak references: after first 2 bullets should guess might have no real idea when object gets released, if @ all, might have no real idea when weak reference gets nulled. think "soon enough".
  • optimisation: there leeway in optimisations compiler can which, while retaining correct semantics of program, may alter lifetime of objects.

if want run these kind of investigations further if (a) use own class types, not libraries , (b) use @autoreleasepool { ... } blocks limit lifetimes of auto-released objects.

as example, when ran code on compiler using did not (null), changing first assignment string0 = text.lowercasestring.mutablecopy did produce one... figuring out why left exercise...

have inquiring mind , explore, good, prepared non-obvious!

hth


Comments