I have the following issue:
I have one instance from class that extends UIViewController class, in this class i am adding UIImage to UIImageView, and then adding the UIImageView to the self.view using this method "addSubview:" [self.view addSubview:imageView] and finally adding the self.view to the window using [[[UIApplication sharedApplication] keyWindow] addSubview:[self view]] , and when i click on a close button i am clearing the self.view (removing the subview "UIImageView") and removing the self.view from the window.
now the issue is when i am using the same instance to add other UIImageView with other image, the first data is not freed from the memory even i have released them and removed them from the superview. the following code illustrates the problem.
- (void) setImageWithURL: (NSString *)url {
NSData * imageData =NSData * imageData =[NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
if (imageData) {
UIImage *image = [[UIImage alloc]initWithData:imageData];
[[[UIApplication sharedApplication] keyWindow] addSubview:[self view]];
[self createViewWithImage:image];
[image release];
}
-(void) createViewWithImage: (UIImage *) image{
[self.view setHidden:false];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
[self.view addSubview:imageView];
[imageView release];
}
// for removing the imageView when i click on close button
-(void) closeView{
for (UIView *subView in self.view.subviews) {
[subView removeFromSuperview];
}
[self.view removeFromSuperview];
}
Note: I have used the xcode instruments to test the memory allocation.
UPDATE: after more research .. it is not addSubview & removeFromSuperview that make memory leaks.. its NSData. I dont why its not released from the memory. I have made some changes to test if its truly the NSData, i saved the image locally and set the image using two cases:
//Case 1:
NSString *path = [[NSBundle mainBundle] pathForResource:@"image" ofType:@"png"];
NSData * imageData =[[NSData dataWithContentsOfFile:path];
image = [[UIImage alloc]initWithData:imageData];
//Case 2:
NSString *path = [[NSBundle mainBundle] pathForResource:@"image" ofType:@"png"];
image = [[UIImage alloc] initWithContentsOfFile:path];
I have found that case one makes memory leaks, while case 2 is clean.
now UIImage cant take the image without using the NSData, and for some reason NSData is not released .. so how can i fix this problem !!!!