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
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.
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.
This may sound a newbie question, however I'm new to iOS dev.
Suppose with have this code.
UILabel* label = [[UILabel alloc] init];
...
[someScrollView addSubview:label];
...
label.text = #"Some Text";
is it good practice to modify the view after addSubview ?
Actually my concern is following probably, it is possible that label get released before reaching to label.text assignment, for instance in viewDidUnload, right ? and the assignment will fail.
Overall my questions are
it is good practice to modify views after addSubview ?
is it good practice to release view after addSubview, and later if I need to get any subview to look for it using following technique for (UIView *view in self.subviews) { if (...) ... } ?
It is fine to change properties of a view after you add it as a subview. Those properties will be applied (or animated) on the next turn of the runloop when UIKit renders stuff.
You should absolutely release your view after adding it as a subview IF you no longer need to own it. In other words, follow the memory management guidelines for all cocoa programming. Doing addSubview will cause the owing view to retain it (since it needs it). If you need to change a property on the view in the future though, you should retain it so you have access to it
Your code is fine as long as it is all in the same method and label is not reassigned during any of the ... sections.
Modifying a view before or after adding it to a subview makes no difference.
If you have allocated a view, then added it to a subview, and you don't wish to keep a separate reference to it, you should release it - this is standard memory management. The super view will retain its subviews.
To get hold of a reference to your subview again, your two options are:
Set the tag on the subview before adding it, then use viewWithTag: to get it later
Keep a reference to the subview as an instance variable (in this case, you wouldn't be releasing it after creating it, you'd release it on dealloc).
I’ve used both ways - modifying before and after and have not had any issues either way. The superview is retaining the subview, so if you don’t release the superview or set the subview to NIL somewhere, you’re pretty safe.
Yes, you need to release the view you added after addSubview, but easiest to do it like this:
UILabel* label = [[[UILabel alloc] init] autorelease];
Then it will be released automatically and you don’t have to worry about explicitly releasing it.
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.
Is it a leak if I have a view controller and allocate the view like this:
self.view = [[UIView alloc] initWithFrame:frame];
Do I need to do something like this:
UIView *v = [[UIView alloc] initWithFrame:frame];
self.view = v;
[v release];
Yes, the second one. Properties (self.view) retain their value usually.
Yes, it's a leak. Your solution is correct, or you can do:
view = [[UIView alloc] initWithFrame:frame];
Where view is an instance variable. But it's not such good practice. As commented below, in a UIViewController view is a superclass property, so my code example is doubly wrong. However, the principle that self.variable is invoking setVariable:, and will observe the retain style of the property declaration is worth noting. In such cases you can directly assign to the instance variable above, which omits the retain - and makes such code a horror to maintain, which explains why Apple's Objective C 2.0 property syntactic sugar isn't universally admired.
Corrected because Georg was entirely correct.
This depends on the declaration of the view property. If it's not a (retain) property, then you're fine. If it is a retaining property, you must call release.
You need to read the Cocoa Memory Management Rules.
You obtained the object with +alloc. Therefore, according to the rules, you are responsible for releasing it. Your own solution is perfectly fine, or you could do:
self.view = [[[UIView alloc] initWithFrame:frame] autorelease];
There is a very simple rule for Objective-C memory management. If you've sent retain message, you've to send release also. I do not know exceptions with this rule is SDK itself.
Here we've alloc, that sends retain itself (always), so you have to release object somewhere. You can do it in dealloc or right here, after assigning it to self.view.
In objective c, we need to maintain retain count of an object as zero after its purpose. So here in your code you must release the object. Then it will not create any leakage problems.
The second one you specified is the right way. It is not a compulsory , it is the way to express how effective our code is.