@interface:
UIImageView *myImageView;
@property (nonatomic, retain) UIImageView *myImageView;
@implementation:
@synthesize myImageView;
- (void)viewDidLoad
{
[super viewDidLoad];
self.myImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
}
What is the reference count for myImageView? 2 (1 from alloc, 1 from dot notation retain) or 3 (1 from alloc, 1 from dot notation retain, 1 from @property retain)
Do these two statements have the same reference count?
self.myImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
and
myImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
Also, I assume you release them in @implemenation and in dealloc method, correct?
EDIT:
I didn’t get the answer that I wanted, maybe my question is vague. I understand what dot notation, @property, @synthesize, and how setter and getter works. What I don’t understand is what happen when using “self.” and without “self.” regarding retain count. I actually ran retainCount method on myImageView object and it confirms my original, the “self.” case has a retain count of two off the bat (with alloc and property retain so it’s probably a good idea to use autorelease there). Now this lead to another question, if I were not to use autorelease, how do I go about this? release once in viewDidLoad and once more in dealloc would still result in a memory leak, right?
self.myImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
NSLog(@"retain count dot: %d", [myImageView retainCount]);
2011-05-17 10:01:14.915 Test[1249:207] retain count dot: 2
myImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
NSLog(@"retain count: %d", [myImageView retainCount]);
2011-05-17 10:03:14.715 Test[1278:207] retain count: 1
First: you shouldn’t make any assumptions about the reference count. It will be misleading at best.
If you use the property access (
self.myImageView = ...) then it will get retained automatically, thus you are leaking the UIImageView in viewDidLoad. You should use something likeYour last example (without the “dot” access) will modify the ivar directly, so it will not leak this new instance. BUT it will leak the old imageView that you override if you don’t release it before.
I strongly recommend using the property access all the time. And don’t forget to clean up in dealloc:
Some people prefer
self.myImageView = nil;but this may have side effects.