objective c - Weak NSString variable is not nil after setting the only strong reference to nil -
i have problem code :
__strong nsstring *yourstring = @"your string"; __weak nsstring *mystring = yourstring; yourstring = nil; __unsafe_unretained nsstring *theirstring = mystring; nslog(@"%p %@", yourstring, yourstring); nslog(@"%p %@", mystring, mystring); nslog(@"%p %@", theirstring, theirstring);
i'm expecting pointers nil
@ time, not , don't understand why. first (strong) pointer nil
other 2 not. why that?
tl; dr: problem string literal never gets released weak pointer still points it.
theory
strong variables retain value point to.
weak variables won't retain value , when value deallocated set pointer nil (to safe).
unsafe unretained values (as can read name) won't retain value , if gets deallocated nothing it, potentially pointing bad piece of memory
literals , constants
when create string using @"literal string"
becomes string literal never change. if use same string in many places in application, same object. string literals doesn't go away. using [[nsstring alloc] initwithstring:@"literal string"]
won't make difference. since becomes pointer literal string. worth noting [[nsstring alloc] initwithformat:@"literal string"];
works differently , release string object.
line line:
__strong nsstring *yourstring = @"your string";
you creating strong pointer string. ensure value not go away. in case it's little bit special since string string literal technically won't released.
__weak nsstring *mystring = yourstring;
you create weak pointer same thing strong pointer. if @ time strong pointer point else, value pointing deallocated, weak pointer change value points nil
. still points same strong pointer.
yourstring = nil;
your strong pointer points nil
. nothing points old string should released if it wasn't fact literal string. if tried exact same thing other objects created yourself, weak variable change points nil
. but, since string literal literal , doesn't go away. weak variable still point it.
__unsafe_unretained nsstring *theirstring = mystring;
a new unretained pointer created, pointing weak pointer pointing string literal.
nslog(@"%p %@", yourstring, yourstring); nslog(@"%p %@", mystring, mystring); nslog(@"%p %@", theirstring, theirstring);
you print strings , confused why first value nil
other 2 aren't.
Comments
Post a Comment