Memory leak in image - objective-c

I'm using the profiler in xcode 4 to determinate if I have any memory leaks. I didn't have this leak before, but with xcode 5 I have this one.
I'm trying to set an image for the tab item of my `UIViewController and the profiler marks this line :
image = [[UIImage alloc] initWithContentsOfFile:imgPath]; <<=== Leak : 9.1%
This is part of my code I don't understand why. What's the best way to resolve this issue?
NSString *imgPath;
UIImage *image;
IBNewsViewController *newsView = [[IBNewsViewController alloc] initWithURL:[tvLocal urlFlux] title:#"News" isEmission:NO];
[newsView setTitle:#"News"];
imgPath = [[NSBundle mainBundle] pathForResource:"news" ofType:#"png"];
image = [[UIImage alloc] initWithContentsOfFile:imgPath]; <<=== Leak : 9.1%
newsView.tabBarItem.image = image;
[image release];
image = nil;
UINavigationController* navNew = [[UINavigationController alloc] initWithRootViewController:newsView];
[newsView release];
newsView = nil;
EDIT:
No leak on iOS6.
Why it's leak on iOS7?

You should switch to the autoreleasing imageNamed: method. This has the added benefit of system level cacheing of the image.
NSString *imgPath;
UIImage *image;
IBNewsViewController *newsView = [[IBNewsViewController alloc] initWithURL:[tvLocal urlFlux] title:#"News" isEmission:NO];
[newsView setTitle:#"News"];
image = [UIImage imageNamed: #"news"];
newsView.tabBarItem.image = image;
UINavigationController* navNew = [[UINavigationController alloc] initWithRootViewController:newsView];
[newsView release];
newsView = nil;
To make life easier on yourself I'd switch your project to use ARC so you have less to worry about WRT memory management.

Replace this line
image = [[UIImage alloc] initWithContentsOfFile:imgPath];
With
image = [UIImage imageWithContentsOfFile:imgPath];
and check once.

First, switch to ARC. There is no single thing you can do on iOS that will more improve your code and remove whole classes of memory problems with a single move.
Beyond that, the code above does not appear to have a leak itself. That suggests that the actual mistake is elsewhere. There are several ways this could happen:
You're leaking the IBNewsViewController somewhere else
IBNewsViewController messes with its tabBarItem incorrectly and leaks that
You're leaking the UINavigationController somewhere else
You're retaining the tabBarItem.image somewhere else and failing to release it
Those are the most likely that I would hunt for. If you're directly accessing ivars, that can often cause these kinds of mistakes. You should use accessors everywhere except in init and dealloc. (This is true in ARC, but is absolutely critical without ARC.)
Leak detection is not perfect. There are all kinds of "abandoned" memory that may not appear to be a leak. I often recommend using Heapshot (now "Generation") analysis to see what other objects may be abandoned; that may give you a better insight into this leak.
Why differences in iOS 6 vs iOS 7? I suspect you have the same problem on iOS 6, but it doesn't look like a "leak", possibly because there is something caching the image that was removed in iOS 7. The cache pointer may make it look like it's not a leak to Instruments.
Speaking of which, do make sure to run the static analyzer. It can help you find problems.
And of course, switch to ARC.

Related

Potential leak IPhone App

HarrisAnnotation *harrisAnnotation = [[HarrisAnnotation alloc] init];
[self.mapAnnotations insertObject:harrisAnnotation atIndex:0];
[harrisAnnotation release];
Running analyze on project show
Potential leak of an object
for
harrisAnnotation
Never mind, I'm not used to using Xcode. It was the line below.

NSImageView - Huge memory leak?

For some reason, the allocation of two NSImageViews creates a huge memory leak.
Although dealloc method gets called in both NSImageViews.
I'm using ARC.
With NSImageViews
As soon as the following getter method is called, a lot of memory is used.
This would be ok, but it doesn't get deallocated when the window is being closed...
- (NSView *)animationView {
if (!_animationView) {
_animationView = [[NSView alloc] initWithFrame:self.bounds];
self.oldCachedImageView = [[NSImageView alloc] initWithFrame:self.bounds];
[_animationView addSubview:self.oldCachedImageView];
self.oldCachedImageView.wantsLayer = YES;
self.cachedImageView = [[NSImageView alloc] initWithFrame:self.bounds];
[_animationView addSubview:self.cachedImageView];
self.cachedImageView.wantsLayer = YES;
self.animationView.wantsLayer = YES;
}
return _animationView;
}
The first circle is when the getter method above is called.
The second is when the window is deallocated.
Without NSImageViews
Not with the two NSImageViews commented out.
- (NSView *)animationView {
if (!_animationView) {
_animationView = [[NSView alloc] initWithFrame:self.bounds];
/*
self.oldCachedImageView = [[NSImageView alloc] initWithFrame:self.bounds];
[_animationView addSubview:self.oldCachedImageView];
self.oldCachedImageView.wantsLayer = YES;
self.cachedImageView = [[NSImageView alloc] initWithFrame:self.bounds];
[_animationView addSubview:self.cachedImageView];
self.cachedImageView.wantsLayer = YES;
self.animationView.wantsLayer = YES;
*/
}
return _animationView;
}
No memory leak here...
Anyone an idea why this happens?
Use Instruments to trace the "Leaks". There is a Leaks tool in Instruments. Run it through the use of your app, all the way until you close your it completely. Make sure ARC isn't just deallocating it at a later time, which is possible. Keeping it in memory for a while allows for a faster retrieval if needed again.
However, if you do see a leak displayed, then there is an issue. Make sure there are no references to it you aren't noticing.
Use the leaks tool to figure out the memory location that is leaking if it displays some. Then try to match it with some object in your code. In other words, make sure it is the NSImageView that is leaking.
You can use:
NSLog(#"Location = %#",NSObjectHere);
To get the memory location. If it matches, then go back, once more, and find the reference you have to it. Unless it's an ARC bug, which is possible, though unlikely, then you are holding a reference to it somewhere.
For any more detail, please update your question with more code, no one can debug it for you without seeing more code.
Good luck!
EDIT
Tutorial explaining the use of the Leaks tool at http://mobileorchard.com/find-iphone-memory-leaks-a-leaks-tool-tutorial/

OS X ARC memory increase in repeated image loading

I have come across an issue when loading different NSImages repeatedly in an application written using Automatic Reference Counting. It seems as though ARC is not releasing the image objects correctly, and instead the memory usage increases as the list is iterated until the iteration is complete, at which point the memory is freed.
I am seeing up to 2GB of memory being used through the process in some cases. There's a good discussion on SO on a very similar issue which ends up putting the process in an NSAutoReleasePool and releasing the image and draining the pool. This works for me as well if I don't use ARC, but it is not possible to make calls to these objects / methods in ARC.
Is there any way to make this work in ARC as well? It seems as though ARC should be figuring this out all by itself - which makes me think that the fact that these objects are not getting released must be a bug is OS X. (I'm running Lion with XCode 4.2.1).
The kind of code which is causing the issue looks like this:
+(BOOL)checkImage:(NSURL *)imageURL
{
NSImage *img = [[NSImage alloc] initWithContentsOfURL:imageURL];
if (!img)
return NO;
// Do some processing
return YES;
}
This method is called repeatedly in a loop (for example, 300 times). Profiling the app, the memory usage continues to increase with 7.5MB alloced for each image. If ARC is not used, the following can be done (as suggested in this topic):
+(BOOL)checkImage:(NSURL *)imageURL
{
NSAutoReleasePool *apool = [[NSAutoReleasePool alloc] init];
NSImage *img = [[NSImage alloc] initWithContentsOfURL:imageURL];
if (!img)
return NO;
// Do some processing
[img release];
[apool drain];
return YES;
}
Does anyone know how to force ARC to do the memory cleaning? For the time being, I have put the function in a file which is compiled with -fno-objc-arc passed in as a compiler flag. This works OK, but it would be nice to have ARC do it for me.
use #autoreleasepool, like so:
+(BOOL)checkImage:(NSURL *)imageURL
{
#autoreleasepool { // << push a new pool on the autotrelease pool stack
NSImage *img = [[NSImage alloc] initWithContentsOfURL:imageURL];
if (!img) {
return NO;
}
// Do some processing
} // << pushed pool popped at scope exit
return YES;
}

Can I use autorelease to fix this memory leak?

I have a memory leak in my iPhone app. I added Google AdMob to my app using sample code downloaded from Google. However, I was having a hard time getting it into testing mode so I added an extra variable as follows:
GADRequest *r = [[GADRequest alloc] init];
r.testing = YES;
[bannerView_ loadRequest:r];
I found the memory leak using Instruments. Instruments does not lead me to this line of code, it just dumps me in the main.m file. However, when I comment out the code relating to AdMob the leak goes away and I know enough to see that I haven't taken care of releasing this new variable. I just don't know exactly how I should set about releasing it. The variable r is not addressed in the header file so this is all the code that deals with it.
I tried adding:
- (void)dealloc {
[r release];
....
}
but that caused a build error saying "'r' undeclared". That's weird because it looks to me like I'm declaring r in the first quoted line above but I guess that's wrong. Any help would be much appreciated. I really have tried to educate myself about memory leaks but I still find them very confusing.
Just add [r release]; right below the code:
GADRequest *r = [[GADRequest alloc] init];
r.testing = YES;
[bannerView_ loadRequest:r];
[r release];
The variable r is declared only in that section of your code, so that's where it should be released. The point of releasing is to get rid of it as soon as you no longer need it, so the above should work perfectly for you.
If your r is locally declared (as it seems, judging from your snippet), then it cannot be accessed from outside its scope (here: the method it was declared in).
You either need to make it accessible within your class instance by declaring it an ivar.
Declaring it an ivar would look like this:
#interface YourClass : SuperClass {
GADRequest *request;
}
//...
#end
You then change your code to this:
request = [[GADRequest alloc] init];
request.testing = YES;
[bannerView_ loadRequest:request];
Also don't forget to release it in dealloc:
- (void)dealloc {
[request release];
//...
}
However this is not what you want in this situation (I've just included it to clarify why you get the warning about r not being declared).
You (most likely) won't need request any second time after your snippet has run, thus storing it in an ivar will only needlessly occupy RAM and add unwantd complexity to your class. Stuff you only need at the immediate time after its creation should be taken care of (released) accordingly, that is within the very same scope.
What you'll actually want to do is simply (auto)release it, properly taking care of it.
Keep in mind though that your loadRequest: will need to take care of retaining r for as long as it needs it. Apple's implementation does this, of course. But you might want to write a similar method on your own one day, so keep this in mind then.
GADRequest *r = [[GADRequest alloc] init];
r.testing = YES;
[bannerView_ loadRequest:r];
[r release]; //or: [r autorelease];
OP here. Thanks for all the detailed and thoughtful responses. This has definitely helped get a better handle on memory management. I did exactly as recommended, adding [r release]; right below the posted code. However, I still have a leak. I have isolated it to a single line of code. The following leaks:
GADRequest *r = [[GADRequest alloc] init];
r.testing = YES;
[bannerView_ loadRequest:r];
[r release];
The following does not leak:
GADRequest *r = [[GADRequest alloc] init];
r.testing = YES;
// [bannerView_ loadRequest:r];
[r release];
I figure I'm changing the retain count on bannerView with the loadRequest but I don't know how to fix it. I tried a [bannerView_ release] immediately after the [r release]; line (i.e. releasing locally) but that didn't work. I didn't expect it to because bannerView_ is declared elsewhere. I tried [bannerView_ release]; in the dealloc method but that didn't work. I also tried [bannerView_ autorelease]; locally. The wise heads at Google put [bannerView_ release]; in the ViewDidUnload method.
It's possible that Instruments is just messing with my head. The leak appears after about 10 seconds but the app performs well and the amount of memory leaked doesn't seem to be spirally upwards as the app continues to run. Is there such a thing as a benign memory leak?
Thanks again for your help,
Dessie.

Problem with memory management

Here is a sample code, i am trying to import contacts for the iphone to my app.
-(IBAction)import_Clicked:(id)sender{
ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationController alloc] init]; //leaking here
picker.peoplePickerDelegate = self;
// Display only a person's phone, email, and birthdate
NSArray *displayedItems = [NSArray arrayWithObjects:[NSNumber numberWithInt:kABPersonPhoneProperty],
[NSNumber numberWithInt:kABPersonEmailProperty],
[NSNumber numberWithInt:kABPersonBirthdayProperty], nil];
picker.displayedProperties = displayedItems;
[self presentModalViewController:picker animated:YES];
[picker release];}
i ran this on instruments and it shows me 100% leak at line where i alloc abpeoplepickernavigationcontroller. i realsed it after persentmodalviewcontroller. where else could i go wrong.
Any Help , Please.....
There seems to be a strange SDK bug at large here... Have a read of the official Apple dev forums here for more information and a solution.
Strange, that doesn't looks like a leak to me, heard that Instruments (rarely) report false leaks.
EDIT: forget what follows and read bbum comment instead :)
Could you please try removing [picker release] and then use autorelease instead :
BPeoplePickerNavigationController *picker = [[[ABPeoplePickerNavigationController alloc] init] autorelease];
Then see if instruments still report a leak? If not, keep your original code and ignore that false alert...
That is almost the same but using NSAutoReleasePool might change Instruments behavior.
Please also note that explicitly releasing like you did is a more cleaner approach than autoreleasing.