strong references, understanding weak references

Asked 2 years ago, Updated 2 years ago, 91 views

Please.
We are trying various ways to use weak references to prevent circular references.I would like to ask you a question because there is a phenomenon in which the object referenced only by weak reference does not seem to be released.
(Refer to the properties in Apple's Programming with Objective-C)

Make
//date1 refer to the current time (with strong reference).
NSDate*date1 = [[NSDate alloc] init]; 

Make //date2 refer to the same time.(with weak references)
NSDate*__weak date2 = date1; 

Make //date1 refer to another time.(The first reference to the current time disappears.)
date1 = [[NSDate alloc] initWithString: @ "2000-01-0100:00:00 + 0000";  

NSLog (@"date1is%@", date1); // date1 see changed time (January 1, 2000)
NSLog(@"date2is%@", date2); // date2 becomes null

If date2 is weakly referenced as above, date2 will be null if date1 is referenced differently.
Yes, but if you change the code in the first line to the code that generates NSDate, for example,

NSDate*date1 = [[NSDate alloc] initWithString: @ "2000-12-3123:59:59+0000";

Then, if the reference for date1 changes, date2 retains this date and does not become null. Why?Also, even if the data type to be handled is NSSstring type, it does not seem to release objects that are referenced only by equally weak references.Thank you for your cooperation.

objective-c arc

2022-09-30 20:57

1 Answers

NSLog(@"%d", (int)CFGetRetainCount(__bridgeCFTypeRef)date1));

As you can see in the reference counter, initWithString: generates NSDate and returns -1 (no release required).

The condition under which weak references are zeroed is when the reference count for each object managed by runtime is zero, so __weak does not work for objects that are not released.

The same NSDate behaves differently because the class itself generated by the cluster is different.

[NSDate alloc] init];

generates __NSDate.In contrast,

[NSDate alloc] initWithString:@"2015-09-0600:00:00+0000";

The class generated by the is __NSTaggedDate.

This is a private area of the framework, so it's just a guess, but _NSTaggedDate is implemented with tagged pointers (there are many similar guesses).

The advantage of using tagged pointers is that they allow extra pointer bit to have date information to create a heap-friendly implementation that can represent multiple dates in a single instance.


2022-09-30 20:57

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.