6

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?

Sebastian
  • 7,670
  • 5
  • 38
  • 50
Sandeep
  • 7,156
  • 12
  • 45
  • 57

2 Answers2

13

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.

arik
  • 28,170
  • 36
  • 100
  • 156
Sebastian
  • 7,670
  • 5
  • 38
  • 50
  • 5
    Just for pedantry's sake: Retain Count is deprecated, Reference Counts are what you're referring to. As in, Automatic **Reference Counting**. – CodaFi Mar 28 '13 at 07:06
0

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

ARC Introduces New Lifetime Qualifiers

it won't increase the reference count by 1. It does not become an owner of that object but just holds a reference to it. If the object's reference count drops to 0, even though you may still be pointing to it here, it will be deallocated from memory.

(nonatomic, copy, strong, weak)

So here to your weak object it will assign the incoming value to it without retaining it. And as you don't have control over the object's lifetime, The object you are referencing weakly only lives on because at least one other object holds a strong reference to it. Once that is no longer the case, the object gets destroyed and your weak property will automatically get set to nil after used once.

Community
  • 1
  • 1
βhargavḯ
  • 9,786
  • 1
  • 37
  • 59