Understanding Weak Links

I have ARC enabled code

@property (nonatomic, weak) NSArray *a; - (void)viewDidLoad { [super viewDidLoad]; self.a = @[@1, @2]; NSLog(@"ab is %@", self.a); //prints details of array // Do any additional setup after loading the view, typically from a nib. } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; for (id element in self.a) { //empty here NSLog(@"blah"); } // Dispose of any resources that can be recreated. } 

This is the only place I've used self.a This is a test program that I wrote to debug one of my problems.

When do I simulate a warning memory self.a disappears? Why?

+4
source share
2 answers

To understand this, you need to understand the number of links. In Objective-C, each object has a reference count (i.e., the number of strong references to the object). If there are no strong links, the reference count is 0 , and the object will be freed.

self.a = @[@1, @2]; creates an auto-implemented NSArray (meaning that it will be released automatically at a later stage) and sets the value to self.a After autoreleasepool is exhausted, the reference count of this array is 0 (in the absence of other strong links), and it is freed. self.a , which is a weak variable, is automatically set to nil.

If you use [[NSArray alloc] init] to initialize your array and assign it to a weak pointer, the object will be released immediately after the assignment. In NSLog , a will be nil .

 __weak NSArray* a = [[NSArray alloc] initWithObjects:@"foo", @"bar", nil]; NSLog(@"%@", a); 

In Xcode 4.6, the compiler will warn you of the latter case.

+9
source

A weak link does not extend the lifetime of the object it points to and automatically becomes nil

ARC Introduces New Lifespan Qualifiers

it will not increase the number of links by 1. It will not become the owner of this object, but simply save the link to it. If the object reference count drops to 0, although you can still point to it here, it will be freed from memory.

(non-nuclear, copied, strong, weak)

So, here, to your weak object, it assigns a value to it without preserving it. And since you have no control over the lifetime of the object, the object you are referring to weakly lives only because at least one other object has a strong link to it. Once this is no longer the case, the object will be destroyed, and your weak property will automatically be set to zero after use once.

0
source

All Articles