I am newbie to iPhone programming. I am not using Interface Builder in my programming. I have some doubt about memory management, @property topics in iPhone.
Consider the following code
@interface LoadFlag : UIViewController {
UIImage *flag;
UIImageView *preview;
}
@property (nonatomic, retain) UIImageView *preview;
@property (nonatomic, retain) UIImage *flag;
@implementation
@synthesize preview;
@synthesize flag;
- (void)viewDidLoad
{
flag = [UIImage imageNamed:@"myImage.png"]];
NSLog(@"Preview: %d\n",[preview retainCount]); //Count: 0 but shouldn't it be 1 as I am retaining it in @property in interface file
preview=[[UIImageView alloc]init];
NSLog(@"Count: %d\n",[preview retainCount]); //Count: 1
preview.frame=CGRectMake(0.0f, 0.0f, 100.0f, 100.0f);
preview.image = flag;
[self.view addSubview:preview];
NSLog(@"Count: %d\n",[preview retainCount]); //Count: 2
[preview release];
NSLog(@"Count: %d\n",[preview retainCount]); //Count: 1
}
When & Why(what is the need) do I have to set @property with retain (in above case for UIImage & UIImageView) ? I saw this statement in many sample programs but didn't understood the need of it.
When I declare @property (nonatomic, retain) UIImageView *preview; statement the retain Count is 0. Why doesn't it increase by 1 inspite of retaining it in @property.
Also when I declare [self.view addSubview:preview]; then retain Count increments by 1 again. In this case does the "Autorelease pool" releases for us later or we have to take care of releasing it. I am not sure but I think that the Autorelease should handle it as we didn't explicitly retained it so why should we worry of releasing it.
Now, after the [preview release]; statement my count is 1. Now I don't need UIImageView anymore in my program so when and where should I release it so that the count becomes 0 and the memory gets deallocated. Again, I am not sure but I think that the Autorelease should handle it as we didn't explicitly retained it so why should we worry of releasing it. What will happen if I release it in -(void) dealloc method
In the statement - flag = [UIImage imageNamed:@"myImage.png"]]; I haven't allocated any memory to flag but how can I still use it in my program. In this case if I do not allocate memory then who allocates & deallocates memory to it or is the "flag" just a reference pointing to - [UIImage imageNamed:@"myImage.png"]];. If it is a reference only then do i need to release it.
Thanks in advance.