ios - Objective-C ARC and __weak for NSString -


nsstring __weak *string = [[nsstring alloc] initwithformat:@"first name: %@", @"braj"]; nslog(@"string:%@", string);   nsstring __weak *string2=@"hello"; nslog(@"string:%@", string2);  nsstring __weak *string3 =[[nsstring alloc]initwithstring:@"braj"]; nslog(@"string:%@",string3); 

here, first string gives output null , other 2 string objects gives ans hello , braj respectively. confused here how deal __weak reference.

"weak" means pointer variable doesn't hold reference object, pointer allows object deallocated. when happens, pointer set nil.

so first nslog should expect. there no strong reference object, becomes nil immediately.

in second case, have string literal. string literals different: never go away. created using clever trickery means no memory saved if deallocated.

the third case: [[nsstring alloc] initwithstring:astring] clever. doesn't allocate new string if isn't necessary! if astring immutable string, result astring , not new object. passed string literal it, result string literal. case 2 :-)

weak references can become nil when else releases last strong reference object. code never knows might hold strong reference (behind scenes), can never rely on weak reference becoming nil.


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -