iPhone: How Memory works when adding to subview - iphone

A general question: When you add an item to an UIView, does that increase the owner count by 1? Does the main view that you added the item to now becomes an owner as well?
Example:
mainView = [[UIView alloc] init];
UILabel *label = [[UILabel alloc] init];
[mainView addSubview:label] //does this increase owner count by 1?
[label release] //and this decreases it by 1?

You release what you retain/init.
When you call addSubview:, it increases the retain count (or as you say owner count). But that increase belongs to mainView. So it is up to mainView to release the subview some point in the future, not you.
So when you init the label it increases the retain count to 1. When you call addSubview:label it increases the retain count by 1, to 2. Then you release the label, decreasing the retain count back to 1 and counteracting you're previous init.
Then when the label is removed from the mainView its retain count will go back down to 0 and it will be deallocated.
Never use the method retainCount, whether you're just observing it, or acting on it. This method will not display what you expect because of a lot of behind the scenes code. Just don't use retainCount.

Subviews are stored in a NSArray which sends a retain to every object added. In principle, yes the retain count goes as you expect but in reality you can never observe the retain count reliably because of all the retains and releases that occur behind the scenes in the API itself. Trying to track the retain count directly will just lead to grief.
It's better to just follow the rule of if you create an object with new or alloc-init then you release it. If you don't do the former, you don't do the later.

Related

Memory management question

I wanted to clarify something:
I.e when I add a UIVIEW To i.e another UIVIEW programatically.
i.e [theview addsubview:thechildview];
I need to release thechildview because theview increments the retain count.
Right?
So basically if I have a loop and I am using that loop to initialise subviews and add the subviews to a view:
for(int i=0;i<10;i++){
UIView *child = [UIview alloc]init.....
[parent addSubview:child];
[child release];
}
I still need to release the child right ? So that would mean the child view still has a retain count of 1 right ?
The thing is whenever I call the release on the child after adding , the child gets deallocated after a while.
Can you guys confirm am doing the right thing by releasing the child after it is added ?
thanks.
You should release it somewhere, correct. You can hold on it and release it later, but it is your responsibility to do it somewhen.
The parent view will retain/release its childs on its own. So if the parent view gets dealloc'ed, it will release its child views.
If a child view is removed from its superview, it will also be released.
I need to release thechildview because theview increments the retain count.
Right
Wrong.
You need to release theChildView if you own it and if you have finished using it. Whether theview chooses to retain it or not is completely irrelevant.
So if we look at your loop
for(int i=0;i<10;i++){
UIView *child = [UIview alloc]init.....
[parent addSubview:child];
[child release];
}
the code is correct because at the beginning of the loop block you alloc the child which means you own it and at the end of the loop it is about to go out of scope which means you no longer need it so you must release (or autorelease) it.
What happens in between is totally irrelevant and you should not assume anything about what any particular method on another object does (except that it adheres to the Memory Management Rules).
I still need to release the child right ? So that would mean the child view still has a retain count of 1 right ?
You cannot assume anything about the retain count. parent might cause the object to be retained more than once if it hands it off to other objects. It might choose to copy it instead of retaining it. If it doesn't need to keep a reference it might not retain it at all.
Can you guys confirm am doing the right thing by releasing the child after it is added ?
No, you are doing the right thing by releasing it when you have finished using it.

Why does view property of UIViewController increments retainCount on every access?

So this is the question. Why does it do it? Even when I do something like this
NSLog(#"view's retainCount %d", [viewController.view retainCount]);
it increments the retain count.
Don't look at the retain count.
The viewController's getter is holding it for you so it can return a reference for you to (in this case) access the "retainCount" variable. It is returning this reference as "autorelease", so it is not really perminantley holding the retain count.
For example, if you ran this NSlog function 5 times in a row, you might see the retainCount go up by 5, but if you created a UI button that called it - thus giving the autorelease the ability to kick-in between presses of the button - you would not see it going up forever.

EXC_BAD_ACCESS after calling popViewControllerAnimated

I'm getting an EXC_BAD_ACCESS after calling dismissModalViewControllerAnimated on my view controller. My project is based on the table view starter project, and RootViewController creates a view like this:
GobanVC *vc = [[GobanVC alloc] initWithNibName:#"GobanVC" bundle:[NSBundle mainBundle] coll:c];
[self.navigationController pushViewController:vc animated:YES];
[vc release];
In GobanVC.m, I'm handling a button to dismiss the view:
- (IBAction) onDone:(id) sender;
{
[self.navigationController popViewControllerAnimated:YES];
}
For some reason the GobanVC object is getting over-released. I ran the allocation instrument, and I can see the reference count get set to 1 when I call alloc, then UIKit calls retain/release a bunch of times, and then my release above is handled. After that, none of the retain or releases are from my code, and after popViewControllerAnimated, the count becomes -1 eventually.
If I take the release above out, things seem to work okay, so it seems the count is off by exactly one somewhere.
Any ideas?
Maybe there is something wrong with GobanVC. Do you have the implementation for it?
Because if there is a retain for every release made by UIKit (there should be).
And you say that your calls are balanced as well (one alloc and one release).
Then it means that in the implementation of GobanVC there must be something wrong.
Let's count the retains:
Alloc makes it 1.
Release makes it 0.
So, what comes out of the stack when you call pop will have retain counter equal to 0, which is NOT what you want. If you either remove release or keep it and assign "vc" to an instance variable defined as "retain" property, you will be fine.
From the code you provided I can see the following:
Root controller creates an instance of GobanVC. The GobanVC's retain count is 1.
Root controllers pushes GobanVC instance to the navigation stack. I am not sure if push increases the retain count. Most probably yes. Then the retain count of GobanVC instance becomes 2.
You release the GobanVC instance, setting its counter to 1.
Your button handler resides in GobanVC (not in the Root controller). So, GobanVC pops ITSELF from the stack with retain count 0 (because if push increases the counter, pop will decrease it). This IS a problem.

Where I should call [object release]?

I've subclassed some UITextField and added some custom properties.
In a UITableViewController, in the ViewDiDLoad I init them, and in the cellForRowAtIndexPath I add them to the cell with [cell.contentView addSubview:customTextField];
Each cell has a different customTextField as all of them are very different.
Where I should call the [customTextField release] ?
After I add them to the cell view ?
If for example I call [self.tableView reloadData] my customTextField are going to be added again to the cell, so maybe I should change my approach in doing this ?
thanks for the orientation ...
regards,
r.
You release an object when you no longer have any interest in it. This happens for many reasons; it might be because you've finished with the object, or have passed the control over the object lifetime to another object. It might be because you're about to replace the object with a fresh instance, it might be because you (the owner object) are about to die.
The last one seems to be relevant in your case. You create these object in viewDidLoad and repeatedly need them (i.e. to add them to cells) until your object is no longer functioning. In this case, just as you create them in viewDidLoad, you can release them in viewDidUnload.
Edit: I should really mention autorelease, but this isn't relevant in this instance. Memory management is best handled with a notion of 'owner' - the person who creates something (or retains it) should be responsible for deleting it (or releaseing in ObjC parlance). autorelease handle some cases where you need to give an object to an alternate owner, having previously owned it yourself (typically via a method return). If you are the creator, you can't just release it before returning it to the new owner, as it will be deleted before the new owner has a chance to stake an interest in it. However, you can't just not release it; it will leak. As such, the system provides a big list of objects that it will release on your behalf at some point in the future. You pass your release responsibility to this list, then return the object to the new owner. This list (the autorelease pool) ensures your release will occur at some point, but gives the new owner a chance to claim the object as theirs before it's released.
In your case, you have a clear interest in owning the objects for the lifetime of your view controller - you need to, at any time, be able to add them to view cells in response to a table data reload. You're only done with them when your view controller dies, so the viewDidUnload (or possibly dealloc) is the only sensible place to release them.
I always release my controls directly after I added them to a view using addSubView. When I work with tables, I also initialize them in the cellForRowAtIndexPath method.
Therefor the object stays alive the shortest time.
Adam Wright explains the theory of this very well, but let me give you some practice. You're thinking about this problem far too hard, and that almost always leads to bugs. There is a simple solution that solves this problem almost every time: Retain all ivars using accessors; don't retain non-ivars.
.h
#interface ... {
UITextField *_customTextField;
}
.m
#property (nonatomic, readwrite, retain) UITextField *customTextField;
...
#synthesize customTextField=_customTextField;
-(void)viewDiDLoad {
self.customTextField = [[[UITextField alloc] init....] autorelease];
}
...
- (void)dealloc {
// I do not recommend accessors in dealloc; but everywhere else I do
[_customTextField release]; _customTextField = nil;
}
Never access your ivars directly, except in dealloc (even that is controversial and some people recommend self.customTextField = nil; in dealloc; there are arguments either way). But never assign your ivars directly. If you will follow this rule, you will find that most of your memory problems go away.
The safest way to handle object ownership is to autorelease the view directly after initialization:
FooTextField* textField = [[[FooTextField alloc] init] autorelease];
[myCell.contentView addSubview:textField];
Adding the text field to a superview (the UITableViewCell's contentView) retains it. This way you don't have to care about releasing the view afterwards.
There seems to be a resentment against autorelease in the iPhone developer community. In my opinion, this resentment is unfounded. Autoreleasing an object adds very little overhead to the program if the objects lives longer than the current pass through the run loop.
Every object in Obj-C has a reference counter (retainCount), and when this counter goes to 0 the object is deallocated. When you allocate and initialize an object, the reference count is set to 1 - but you can retain it as many times you want to.
UITextField *textField = [[UITextField alloc] init]; // Reference counter = 1
[textField retain]; // Reference counter = 2
[textField retain]; // Reference counter = 3
The opposite of retain is release, which subtracts from the reference counter;
...
[textField release]; // Reference counter = 2
[textField release]; // Reference counter = 1
You can always get the reference counter of your objects;
printf("Retain count: %i", [textField retainCount]);
The method addSubview of UIView does retain your passed in sub view - and when it's done with it it releases it. If you need your UITextField later, in another scope (when the UIView is done with it and has released it) - you should not release it after you've added it to the super view. Most of the time you actually don't need to hold on to a reference, so you should release it after you've added it to the super view. If you dont - you can release it in the dealloc method of your scope.
Take a look at UITableView -dequeueReusableCellWithIdentifier: and -initWithStyle:reuseIdentifier:.
In -tableView:cellForRowAtIndexPath:, use -dequeueReusableCellWithIdentifier: and check if the result is nil. If it is, instantiate a new cell with -initWithStyle:reuseIdentifier:.
Send -autorelease to your customTextField upon creation and adding to the respective cell.
You should not add subview in cellForRowAtIndexPath! This will slow down the view as you add a subview each time the cell is displayed. Try using custom UITableViewCell class for that purpose.
Here is a perfect solution of UITableView customization
http://cocoawithlove.com/2009/04/easy-custom-uitableview-drawing.html
works jut perfectly

iphone - generic question about objects

I have several UIImagesView and I put them on a MutableArray. The MutableArray is retained.
I add them also as a subview of a view.
After adding each UIImageViews on a view I release them... for example...
[myView addSubview:myImageView];
[myImageView release];
If I am not wrong, each imageView has now a retainCount of 2, because they are also stored on the MutableArray.
Now I release the view, so, each imageView retainCount drops to 1.
At some point I do:
myMutableArray = nil;
is it OK to do that? As the imageViews have yet a retainCount of 1, I am not sure if putting the array to nil, the array which were storing the imageViews will release the images... I suppose so, but I would like to hear from you masters!
will this leak?
thanks
You should ignore retain counts because the system adds and removes retain count behind the scenes and you can't possibly track it.
Instead, you need to focus on matching the retains and releases pairs you yourself create.
In this case, the only thing you need to pay attention to is the possible retain of initializing the image views in the first place.
Usually it looks something like this:
UIImageView *imgView=[[UIImageView alloc] initWithImage....
[myMutableArray addObject:imgView];
[myView addSubview:imgView];
[imgView release];
And you're done. The array and view will manage their own retention and you matched the retain of your initialization with a release and all is right with the world.
Yes that will leak! You are setting myMutableArray to nil without releasing the array. Doing so will leak the memory from the NSMutableArray object AND all of the UIImageView objects that it contained. If you want to dispose of the array and its contents, then release the array just like you would release any other object:
[myMutableArray release];
myMutableArray = nil;
The array will then send a release message to each object that it contains.