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:

  1. 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); }); 
  2. you should wary of evaluating memory behavior using nsstring. in case, don't think matters, in other cases nsstring sorts of optimizations , caching can affect behavior. i'd suggest testing nsobject or nsobject subclass.


Comments

Popular posts from this blog

node.js - Mongoose: Cast to ObjectId failed for value on newly created object after setting the value -

[C++][SFML 2.2] Strange Performance Issues - Moving Mouse Lowers CPU Usage -

ios - Possible to get UIButton sizeThatFits to work? -