I did not understand the weak and strong links

The books first explain the problem (using ARC) about "invalid" links, as in this example:

NSDate* date1=[[NSDate alloc]init];
NSDate* date2=date1;
[date1 release];
NSLog(@"%@",date2); // bad access

So, I understood the save / release mechanism: in this case, the instruction will be:

date2=[date1 retain];

But when it comes to strong / weak links, it sounds like a contradiction with me:

"By default, links are strong. If you assign an object to a strong link, ARC assumes that you want this object to stick and persist implicitly."

Is this not a contradiction to what has been said before?
date2 is strong by default, so it must implicitly save date1, and there would be a bad access exception.
Of course, I didn’t understand something, can someone explain this to me better?

+3
2

, , , ARC, , , . :

- (void)someMethod
{
  NSDate* date = [[NSDate alloc] init]; // date is __strong by default
  NSLog(@"The date: %@", date); // date still contains the object created above

  // Sometime before this point, the object date pointed to is released by the compiler
}

, . , , () nil . , . :

- (void)someMethod
{
  __weak NSDate* date = [[NSDate alloc] init]; // The date created is released before it ever assigned to date 
                                               // because date is __weak and the newly created date has no 
                                               // other __strong references
  NSLog(@"The date: %@", date); // This always prints (null) since date is __weak
}

, ( ):

- (void)someMethod
{
  NSDate* date = [[NSDate alloc] init]; // date stays around because it __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: %@", date); // prints (null) as expected
  NSLog(@"Weak Date: %@", weakDate); // also prints (null) since it was weak and there were no more strong references to the original object
}
+15

, - ARC . . ARC , , .

retain. :

NSDate* date1=[[NSDate alloc]init];
NSDate* date2=date1;
NSLog(@"%@",date2);

ARC; . .

, , . :

NSDate* date1; // date1 initialized to nil -- or not given that it is never read before...
date1 = [[NSDate alloc]init]; // ... this assignment (of a +1 retain count obj)
NSDate* date2=date1; // retain count unchanged
NSLog(@"%@",date2); // retain count unchanged
.... compiler emits equivalent to [date1 release] ...

release , date1 date2, .

+3

All Articles