automatic ref counting - Understanding ARC in iOS -
i have block of code have written test arc. set string s2 weak , assign value of s1. then, set s1 nil. assuming since background block executed @ later time, s2 dealloced then. but, when run code, nslog still prints value of s2 "123". can please explain me why happens?
- (void)testarc { nsstring *s1 = [nsstring stringwithformat:@"123"]; __weak nsstring *s2 = s1; s1 = nil; dispatch_async(dispatch_get_global_queue(dispatch_queue_priority_low, 0), ^{ // nslog print? nslog(@"s2 = %@", s2); }); }
two considerations:
you're creating autorelease object isn't released until pool drained. if create non-autorelease object (or use own autorelease pool), won't see behavior, e.g.:
nsstring *s1 = [[nsstring alloc] initwithformat:@"123"]; __weak nsstring *s2 = s1; s1 = nil; dispatch_async(dispatch_get_global_queue(dispatch_queue_priority_low, 0), ^{ // nslog print? nslog(@"s2 = %@", s2); });
you should wary of evaluating memory behavior using
nsstring
. in case, don't think matters, in other casesnsstring
sorts of optimizations , caching can affect behavior. i'd suggest testingnsobject
ornsobject
subclass.
Comments
Post a Comment