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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With