I have this block of code written to check the ARC. I set the straight S2 as weak and it assigns the value of s1. Again, I set the S1 to zero, I was thinking that this background block is executed later, so S2 will already be dealt with by then. But, when I run this code, NSLog still prints the value of S2 as "123". Can anyone explain to me why this happens?
- (zero) testARC {NSString * s1 = [NSString stringWithFormat: @ "123"]; __weak NSString * s2 = s1; S1 = zero; Dispatch_Associc (Dispatch_Get_Global_QUU (DISPATCH_QUEUE_PRIORITY_LOW, 0), ^ {// What will be the NSLog print? NSLog (@ "s2 =% @", s2);}); }
two thoughts:
-
You are building an autorarious object, which is not released until the pool gets deferred. If you create a non-autorizable object (or use your own autorevy pool), then you will not see that behavior, eg:
NSString * s1 = [[NSString alloc ] InitWithFormat: @ "123"]; __weak NSString * s2 = s1; S1 = zero; Dispatch_Associc (Dispatch_Get_Global_QUU (DISPATCH_QUEUE_PRIORITY_LOW, 0), ^ {// What will be the NSLog print? NSLog (@ "s2 =% @", s2);});
-
You should always be wary of evaluating memory behavior by using
NSString
. In this case, I do not think it matters, but in other cases,NSString
will optimize and caching all types that can affect behavior. I suggest testing this with theNSObject
orNSObject
subclass.
No comments:
Post a Comment