I have a UIScrollView in my UIViewController defined as this in my .h file:
#import <UIKit/UIKit.h>
@interface TestViewController : UIViewController <UIScrollViewDelegate>
@property (nonatomic, retain) UIScrollView * imageScrollView;
@end
Then in my .m file I have the following:
@synthesize imageScrollView = _imageScrollView;
I read that this will automatically create the _imageScrollView that I would normally type in the .h file? (UIScrollView * _imageScrollView)
I like it, because it removes duplicate code from my .h files. Now in my loadView I do the rest:
self.imageScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 480.0 - 20.0 - 49.0)];
[_imageScrollView setDelegate:self];
[_imageScrollView setPagingEnabled:YES];
[_imageScrollView setBounces:NO];
[_imageScrollView setShowsHorizontalScrollIndicator:NO];
[_imageScrollView setShowsVerticalScrollIndicator:NO];
[_imageScrollView setContentSize:CGSizeMake(320.0 * 3.0, 480.0 - 20.0 - 49.0)];
And in the dealloc release and nil:
- (void)dealloc
{
[_imageScrollView release], _imageScrollView = nil;
[super dealloc];
}
Now after a build Xcode is telling me this:
Potential leak of an object allocated on line #linenumber
This will go away when I change this:
self.imageScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 480.0 - 20.0 - 49.0)];
to this:
self.imageScrollView = [[[UIScrollView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 480.0 - 20.0 - 49.0)] autorelease];
Why do I need to autorelease this when I’m release it in dealloc? What am I doing wrong?
This memory warning only occurs in Xcode on my iMac with Lion installed, not on my macbook with snow leopard…
It’s because your
imageScrollViewproperty is declared to be aretainproperty. This means that when you set it, the accessor (which is generated by@synthesize) automatically retains the value. If you don’t want this behavior, you should declare your property to beassign. (But you do want this behavior in this case.)Anyway, thus your object is retained twice, once in your code, and once by the accessor, so it’s never released. Always remember that
self.imageScrollView =is just like[self setImageScrollView:], and that stuff happens in there!(And last, the memory warning only occurs on Lion because the old Xcode isn’t noticing the error, not because the error isn’t there.)