Understanding weak reference

16,576

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.

Share:
16,576
Sandeep
Author by

Sandeep

Updated on June 15, 2022

Comments

  • Sandeep
    Sandeep almost 2 years

    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?

  • CodaFi
    CodaFi about 11 years
    Just for pedantry's sake: Retain Count is deprecated, Reference Counts are what you're referring to. As in, Automatic Reference Counting.
  • wz366
    wz366 about 6 years
    Can you explain "get set to nil after used once"?