Reputation: 3230
I am new to Objective-C. Here is my understanding (as in comments) concerning ARC of some simple code for programmatically adding a subview. Please correct me if I am wrong. Especially on this statement:
"ViewController points to myView weakly" ACTUALLY means that _myView (ViewController's ivar) points to a UIView object weakly
// _myView stores a pointer pointing to a UIView object
// "ViewController points to myView weakly" ACTUALLY means that _myView (ViewController's ivar) points to a UIView object weakly
@interface ViewController ()
@property (nonatomic,weak) UIView *myView;
@end
@implementation
@synthesize myView = _myView;
@end
- (void)viewDidLoad
{
[superviewDidLoad];
CGRect viewRect = CGRectMake(10, 10, 100, 100);
// a UIView object is alloc/inited
// mv is a pointer pointing to the UIView object strongly (hence the owner of it)
UIView *mv = [[UIView alloc] initWithFrame:viewRect];
// _myView points to the UIView object weakly
// Now the UIView object now have two pointers pointing to it
// mv points to it strongly
// _myView points to it weakly, hence NOT a owner
self.myView = mv;
// self.view points to the UIView object strongly
// Now UIView object now have THREE pointer pointing to it
// Two strong and one weak
[self.view addSubview:self.myView];
}
// After viewDidLoad is finished, mv is decallocated.
// Now UIView object now have two pointer pointing to it. self.view points to it strongly hence the owner, while _myView points to it weakly.
Upvotes: 1
Views: 159
Reputation: 55563
You are mostly correct, with the exception of this sentence:
After viewDidLoad is finished, mv is decallocated.
That's where you are wrong. Remember, deallocation of an object only ever happens when everyone who retain
's the object release
's it. Thus, while you have release
'd the temporary variable mv
, You still have one other source retaining it: self.view.subviews
. Once mv
is removed from the subview array, it can properly be cleaned up, _myView
is set to nil
, and you have no more leaks.
Upvotes: 3