-1
NSString *strongObj = [[NSString alloc] init]; //alloc and initialze a new instance
strongObj = @"some value"; //set value to a instance
__weak NSString *weakObj = strongObj; //refer strong pointer to weak obj

strongObj = nil; //set strong object to nil and remove it from memory

strongObj = @"some value 2"; //assign a  different value to strong obj

weakObj ; // weak obj still holds  // @"some value" // this value event i've set the week obj pointer to nil

pls look at the above code and comments, the comments are my views/assumptions. Pls clarify.

Thanks

Anoop Vaidya
  • 46,283
  • 15
  • 111
  • 140
skyler
  • 742
  • 1
  • 10
  • 24
  • weak objects will hold the value untill its lifetime and scope are there. After the scope ({ and }) it will be autoreleased and will be added to local or nearest autoreleasepool. then it will be deallocated/freed. – Anoop Vaidya May 21 '14 at 08:41
  • thousands of dupes one is maybe: [Objective-C ARC: strong vs retain and weak vs assign](http://stackoverflow.com/questions/8927727/objective-c-arc-strong-vs-retain-and-weak-vs-assign) – Daij-Djan May 21 '14 at 08:52

2 Answers2

0

String literals are always alive and are never deallocated in runtime. Weak pointer is nullified when memory on which it points is deallocated, so you incorrectly expect your weakObj to be nullified.

To make it work, instead of literal strings you should use

[[NSString alloc] initWithFormat:@"some value %d", 1];

e. g.

NSString *strongObj = [[NSString alloc]  initWithFormat:@"some value %d", 1]; //alloc and initialze a new instance
__weak NSString *weakObj = strongObj; //refer strong pointer to weak obj

strongObj = nil; //set strong object to nil and remove it from memory

weakObj ; 
Eugene Dudnyk
  • 5,553
  • 1
  • 23
  • 48
0

Although you are creating a strongObj instance, you are actually not using the same instance, but are reassigning the pointer to the string literal @"some value", whatever address that is. It is by no means the same instance that you allocate on the first line of your code.

Now when you assign weakObj, you will actually point it to the same string literal @"some value".

What basically happens is that weakObj is not following the strongObj, but it is following the string literal, which is not deallocated. That is why you still see "some value" in there while strongObj has been set to nil.

svena
  • 2,769
  • 20
  • 25