Weak vs Strong References

306 Views Asked by At

What I can understand from weak vs strong references is that:

  • An object is referenced by both strong and weak.
  • While strong doesn't reference to that object anymore, the weak pointer will lose its referenced object.

Then I tried it from this example (taken from other thread in SO) with my full code:

- (void)viewDidLoad
{
  [super viewDidLoad];

  NSDate* date = [[NSDate alloc] init]; // date stays around because it's __strong
  __weak NSDate* weakDate = date;

  // Here, the dates will be the same, the second pointer (the object) will be the same
  // and will remain retained, and the first pointer (the object reference) will be different
  NSLog(@"Date(%p/%p): %@", &date, date, date);
  NSLog(@"Weak Date(%p/%p): %@", &weakDate, weakDate, weakDate);

  // This breaks the strong link to the created object and the compiler will now
  // free the memory. This will also make the runtime zero-out the weak variable
  date = nil;

  NSLog(@"Date(%p/%p): %@", &date, date, date);
  NSLog(@"Weak Date(%p/%p): %@", &weakDate, weakDate, weakDate);
}

I just realize that this doesn't give the expected result:

Date(0xbfffdccc/0x713df20): 2013-12-04 04:19:30 +0000
Weak Date(0xbfffdcc8/0x713df20): 2013-12-04 04:19:30 +0000
Date(0xbfffdccc/0x0): (null)
Weak Date(0xbfffdcc8/0x713df20): 2013-12-04 04:19:30 +0000

Why the second print of weakDate still prints out? Do I have wrong comprehension?

Note:

I am using ARC in Xcode 4.5.1 tested in iOS Simulator iOS 6.0

0

There are 0 best solutions below