Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding weak reference

I have the following 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 where I used the self.a. This is a test program I wrote to debug one of my issues.

When I simulate memory warning self.a vanishes? Why?

like image 530
Sandeep Avatar asked Mar 28 '13 04:03

Sandeep


1 Answers

In order to understand that, you have to understand reference counts. In Objective-C every object has a reference count (i.e. the number of strong references to the object). If there are no strong references, the reference count is 0 and the object gets deallocated.

self.a = @[@1, @2]; creates an autoreleased NSArray (meaning it will be released automatically at a later stage) and assigns that to self.a. Once the autoreleasepool is drained the reference count of that array is 0 (assuming no other strong references) and it gets deallocated. self.a being a weak variable is automatically set to nil.

If you use [[NSArray alloc] init] to initialise your array and assign it to a weak pointer, the object will be released immediately after the assignment. In the 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 about the latter case.

like image 180
Sebastian Avatar answered Oct 12 '22 21:10

Sebastian