Reputation: 2010
Can someone explain the difference between the following (using ARC), where myObj is defined as
@property(nonatomic, weak) MyType *myObj;
Assignment via local variable:
MyType *_myObj = [MyType new];
self.myObj = _myObj;
and
self.myObj = [MyType new];
In the former case, the object instance myObj appears to persist, while in the latter case, the instance is deallocated soon after the enclosing function is complete. What's the difference? Shouldn't they be the same?
[EDIT] I understand that I've specified weak, and my question still stands. Im not sure why this is getting downvoted.
Upvotes: 0
Views: 353
Reputation: 318955
Since your property is defined as weak, the assignment doesn't increase the retain count.
In the second bit of code, you create the object and assign it to the weak property. As soon as this is done, the created object is released and deallocated leaving the weak property reset to nil.
In the first bit of code, you assign the created object to a strong local variable. You then assign the strong local variable to the weak property. As long as the local variable is in scope, the created object has a reference. As soon as the local variable goes out of scope, the object will be released and deallocated leaving the weak property set to nil.
THe end result is the same. When the method competes, the property is left as nil because the created object has no other references to it. The only difference between the two is how quickly this happens.
Upvotes: 4
Reputation: 40018
I have tested it and it result's the same
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//NSObject *_myObj = [NSObject new];
//self.myObj = _myObj;
self.myObj = [NSObject new];
}
- (IBAction)click:(id)sender {
NSLog(@"%@",self.myObj);
}
Both cases results in output as : (null)
Upvotes: 0