In Xcode I have a UINavigationController on wichh I push a UIViewController.
In that UIViewController I init an UIScrollView.
All good.
However, after switching to another view I log the retain count of the controller and to my surprise it's one instead of zero.
Here's the code:
scroller = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
[self.view addSubview:scroller];
and:
- (void)dealloc {
[super dealloc];
NSLog(#"retaincount, %d", [scroller retainCount]); //displays 2
[scroller release];
NSLog(#"retaincount, %d", [scroller retainCount]); // displays 1
}
I only init it ones and add it to the UIViewControllers view.
Kind regards,
Tom
Do not use retainCount! From the apple documentation:
Important: This method is typically of no value in debugging memory management issues. Because any number of framework objects may have retained an object in order to hold references to it, while at the same time autorelease pools may be holding any number of deferred releases on an object, it is very unlikely that you can get useful information from this method.
To understand the fundamental rules of memory management that you must abide by, read “Memory Management Rules”. To diagnose memory management problems, use a suitable tool:
The LLVM/Clang Static analyzer can typically find memory management problems even before you run your program.
The Object Alloc instrument in the Instruments application (see Instruments User Guide) can track object allocation and destruction.
Shark (see Shark User Guide) also profiles memory allocations (amongst numerous other aspects of your program).
Having said that: You have to call [super dealloc] in the very last line of your dealloc method. Besides that everything in your code should be ok. Don't try to manually lower the retainCount. Use proper memory management. Again, do not look at the retainCount.
And you are not allowed to use an object after you have released it. If the scroller would be deallocated because of your release the second NSLog would result in a BAD_ACCESS exception.
self.view is retaining it. When your UIViewController deallocs, it'll release self.view, which will release all its retained subviews. In fact, you should probably release it soon after adding it to self.view.
That said, I strongly second #fluchtpunkt's answer. Examining the retainCount property looking for debugging info will only lead to confusion and increasingly coherent and ranty posts on Stack Overflow.
This is why:
scroller = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
//retain count = 1
[self.view addSubview:scroller];
//retain count + 1 + 1 = 3
//later the AutoreleasePool decrements the count by 1, resulting in a retain count of 2.
Methods beginning with init…
return non-autoreleased instances
with a retain count of 1.
Accessing your
subview via self.view: returnes an autoreleased retained pointer to subview.
Adding a
subview to a view via addSubview: retains the
subview.
Removing a subview from its superview via removeFromSuperview: releases it.
You should not rely on an object's retain count though.
Instead you must take care to level out retain and release calls on an object.
Make sure to read Apple's Memory Management Programming Guide in this matter! (the rules section in particular!)
Previous answers are correct: don't use -retainCount, and make sure that you call [super dealloc] last in your own -dealloc implementation.
I want to add that you'll probably never see a case (not that you should be looking) where -retainCount returns 0. If an object's retainCount drops to zero, the object is deallocated. In fact, it seems that Cocoa never even bothers to set the retainCount to zero... -release appears to deallocate the object if the previous retainCount was 1. Just one more reason to consider -retainCount to be a private implementation detail.
Related
I'm converting a library to ARC atm. where I have an NSViewController descendant that loads a xib the usual way:
- (instancetype)initWithModule: ...
{
self = [super initWithNibName: #"mynib" bundle: [NSBundle bundleForClass: [self class]]];
if (self != nil) {
[self view];
}
return self;
}
When I executed this without ARC the retain count of that controller is 2 after the call to view (which loads the nib and connects the outlets, as you know). However with ARC enabled this increases the retain count to 3, which later causes this controller to leak, because the count never goes back to 0.
I changed all outlets to use weak references (except for NSTextView instances, but they never appear as top level objects). But this doesn't seem to help.
Update: It seems to affect every view controller I have, at least all those I checked. So this seems to be a fundamental problem, not related to the xib content.
How can I find out what causes the additional retain on load?
The absolute retain count is meaningless. You need to find all the spots where retain is called (or called by implication, in the case of ARC).
To do that, use the Allocations instrument and turn on reference count tracking. That'll give you access to the backtrace of every single retain and you can find the extra one.
More likely than not it'll be a strong reference to self in a block held by something in self. Or it'll be a cycle of strong references; self -> other -> self kinda thing.
-(void)NewButton
{
ApplianceViewController *VC = [[ApplianceViewController alloc] initWithNibName:#"ApplianceViewController" bundle:[NSBundle mainBundle]] ;
NSLog(#"Retain count before pushViewController:%d",VC.retainCount);//prints1
[self.navigationController pushViewController:VC animated:YES];
NSLog(#"Retain count after pushViewController:%d",VC.retainCount);//prints 7
[VC release];
NSLog(#"Retain count after Release:%d",VC.retainCount);// prints 6
}
In my code retain count increases abnormally. I waisted lot of time. any help please.
The absolute retainCount of an object is meaningless.
See: http://www.whentouseretaincount.com for more details.
The retain counts you are seeing are internal implementation details of the frameworks. They are, effectively, meaningless. More likely than not, the retain count is as high as it is in that code because you are tangling the view controller into an animation, which requires multiple references and some complex behind the scenes issues.
The code you posted is not the problem.
Use the Allocations instrument with "track live references only" and "track reference counts" turned on. Then reproduce your leak and click through to the inventory of retain/release events for the object in question. That'll give you a list of exactly where the object is retained (and released) which will tell you exactly why it is still in memory.
Actually I have one property
#property(nonatomic, retain) IBOutLet UITableView myTableView;
I was getting reference from nib file. I've just replaced retain with assign. And problem was solved.
-(void)viewDidUnload
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:LASTUPDATEDLOCATION object:nil];
[self setHeaderViewofWholeTable:nil];
[self setFooterViewofWholeTable:nil];
[self setHeaderActivityIndicator:nil];
[self setFooterActivityIndicator:nil];
[self setLastUpdated:nil];
[self setLblPullDowntoRefresh:nil];
[self setRefreshArrow:nil];
[self setContainerForFormerHeader:nil];
[self setFooterContainer:nil];
[super viewDidUnload];
}
I thought viewDidLoad is called the view itself goes nil. When we set the view to nil, wouldn't all those things automatically become nil?
What am I misunderstanding?
Before ARC you needed to manually release objects that you allocated. Setting a property that is marked retain to nil does the releasing. This is no longer necessary when you use the Automatic Reference Counting (ARC) feature, which is on by default in the compiler that comes with recent versions of Xcode.
Good news. As of iOS 6, viewDidUnload has been deprecated. In iOS 5 and earlier, when memory was low there was a chance that your view might have been unloaded (and to make sure there were no memory leaks, you released IBOutlets in this method). But this is no longer called in iOS 6, and thus, no longer a requirement.
Now if there is a issue with memory, your view controller can override:
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
Some of the other answers cover some of this but there is more to this. A view controller will have its viewDidLoad method called. Typically this results in IBOutlets being retained and possibly lots of other views and objects being allocated and retained. If all goes well, eventually the view controller is deallocated and all of those retained objects need to be released.
That's the simple, happy path. Under low memory conditions, in iOS 5 and earlier, it is possible that a view controller's view will be unloaded. The viewDidUnload method was a chance for you to clean up all of the other objects that were retained as part of the viewDidLoad process. And here's the main reason - at some point, viewDidLoad may be called again to redisplay the view controller's view.
Most people write their viewDidLoad method like it will only ever be called once. And this is OK if the viewDidUnload method properly clears up objects. If it doesn't, the next call to viewDidLoad will result in a bunch of memory leaks.
ARC pretty much eliminated the issue with the memory leaks if you didn't clean things up properly in viewDidUnload. But viewDidUnload was still helpful for cleaning up memory when needed.
As was mentioned, as of iOS 6, a view controller's view in never unloaded in low memory conditions and the viewDidUnload (and viewWillUnload) methods have been deprecated.
If your app still supports iOS 5 along with iOS 6, you still need to make proper use of viewDidUnload. But if you want to free up memory when needed, use didReceiveMemoryWarning.
We set so many things to nil to free up as much memory we can and reduce processor strain and increase battery life, not all objects automatically remove themselves from the queue.
I'm getting an strange case of excessive retain counts for a view controller that I'm loading when a button is pushed.
This is the code:
-(IBAction)new
{
if (!viewSpace)
viewSpace = [[ViewSpace alloc] initWithNibName:#"ViewSpace" bundle:nil];
viewSpace.delegate = self;
viewSpace.view.frame = CGRectMake(0, 0, viewSpace.view.frame.size.width, viewSpace.view.frame.size.height);
[self presentModalViewController:viewSpace animated:YES];
NSLog(#"Count Retain: %d",[viewSpace retainCount]);
}
-(void)viewSpaceWasDissmissed:(id)sender
{
[self dismissModalViewControllerAnimated:YES];
[viewSpace release];
NSLog(#"Count Retain: %d",[viewSpace retainCount]);
}
When the IBAction New is executed first time, the retain count is 5 when just is created. (It must be 1).
When the ViewSpace object must be unload calls viewSpaceWasDismissed function in order to remove the modal view and release the previous object.
The problem is that never the retain count reach 0 and the dealloc method of ViewSpace never is called causing memory leaks.
My question is how is possible that a recently created ViewController have 5 retains? I made sure that is never created before.
Thanks.
Cocoa is probably retaining the view controller 4 times internally for reasons of its own. This isn't a problem.
More generally, the -retainCount method is useless for reasons like this, and you should never call it. It will not help you, and it will confuse you.
To debug your leak, I suggest using the leaks Instrument, inspecting the object, and analyzing where each retain and release is coming from to determine whether any are incorrect.
Check the documentation for -retainCount. I believe it says that you should not be calling it yourself - you just need to take care of any retains that you cause, and don't worry about the 'actual' retain count.
You're doing two things wrong here:
The Current view controller retains the modally presented view controller and releaseds it when it is dismissed. So you should release viewSpace after it is presented, and you don't need the release message in the dismissModalViewController method. As an aside ViewSpace is a poor name for a view controller. I had to read to the line where you are presenting it as a view controller before I knew it was a view controller. I think ViewSpaceController is a more descriptive name.
You are using retainCount which is always a bad idea. All that matters is that in your new method you created an owned object (with the alloc) and you balanced that ownership with a release (or at least you will do when you put in the correction I suggested in point 1) That's it. You took ownership of an object and you released it. The retainCount method tells you absolutely nothing that can be of any use to you. Don't do it. Just balance ownerships with release, and that is all that matters.
I'm not 100% sure of every count but here are some:
Instantiation - 1
NIB - 1+
Strong Properties (1+)
Additionally any properties that list it as a strong property (in ARC).
I noticed that when you launch a nib and you use components of the controller in the nib design, it will increase reference counts (in a strong manner) on the controller instance.
does this retain my subview twice?
- (void)viewDidLoad
{
CGRect frame=CGRectMake(0, 0, 320, 460);
mapButtons*newButtons=[[mapButtons alloc] initWithFrame:frame];
self.mapButtons=newButtons;
[newButtons release];
[self.view addSubview:self.mapButtons];
[self.mapButtons addButtons:#"yo"];
once it is added to the view hierarchy with addSubview, does it get an additional retain count beyond that retained by the ivar, self.mapButtons?
i want to be able to manipulate this subview easily, hence the ivar; is this a good way, or is there a better way?
EDIT
You mention memory-wise so I think it may need some clearing up. Each object has a retain count which is incremented with retain and decremented with release. When the retain count reaches 0 a dealloc message is sent. So when you put an additional retain on an object you are not using anymore memory you are simply incrementing the counter and not doing any kind of duplication.
There are a couple of ways you can grab a reference to a view but the way you are doing it is a good way. An alternative would be to tag the view and retrieve it from self.view using
UIView *view = [self.view viewWithTag:tagId];
I prefer the ivar way e.g. how you have done it (this will change when ARC comes in) but I tend not to worry about the the actual retain count of an object. I concentrate on balancing my retain/releases.
Therefore I use the rule that if it's a local variable I try as far as possible to match my retain/release's within the scope it is defined in. The exception being ivar which are released in dealloc