Does this have to be released? - iphone

I've done a lot of research on when it's correct to release things, but it's all confusing to me. I think sometimes the Leaks program is off. Anyway...
background is a UIImageView
background.image = [UIImage imageNamed:#"greenbackground.png"];
Do I have to release background? I never alloced it and it's not set as a property, so I'm thinking no.

Actually, you do need to release it.
UIKit uses Key Value Coding to assign IBOutlets to a controller. By default this is causing your controller to increase the retain count by one. From the KeyValueCoding docs:
If you have not defined a setter, then UIKit will directly set the value of the instance variable and then, for anything other than an NSNumber or NSValue date type, UIKit will retain the value after autoreleasing the instance variable’s old value.
Unless you explicitly set a #property with assign, you need to release the object.

No you don't. That factory method returns an autoreleased UIImage. A good rule of thumb that helps me in objective c is whenever you see alloc, copy or new in a method name... you are incharge of releasing the returned object... everything else should be an autoreleased object. Also, I can't think of any class level methods (+) in the api that don't return autoreleased objects.
EDIT
I read your question too quickly... Mark is correct on this. If you are ever in doubt about these kinds of things you can always do a simple test and log the retain count.

Mark's right that you are responsible for releasing your UIImageView if it is instantiated from a nib, if background is an IBOutlet, and if background does not have a corresponding "assign" property.
Even if you're managing that correctly, you may still see some extra memory in use in ObjectAlloc after you release your UIImageView. That's because -[UIImage imageNamed:] caches the image you load in anticipation of you calling -[UIImage imageNamed:] again later. The image is not necessarily uncached even when the returned UIImage gets deallocated.

Related

Cocoa touch - Memory Management

I am a former java programmer, and I am having some troubles managing the memory on cocoa touch.
In fact, I think I got the retain/release trick, but still I am not sure I got it right.
For example, I am creating and adding a subview to the main window:
aViewController=[[AViewController alloc]init];//aViewController is (nonatimic,assign), so retaincount = 1 after this line?
[self.window addsubview aViewController];
[aViewController release];//retaincount=0?
And in aViewController I have an IBAction:
[self.view removeFromSuperView];
How can I be sure the object aViewController gets completely 'deleted' and memory released after I removed it from superview (think that controller as a graphic-heavy view controller)?
Also, generally, is there a way to be sure an object is deallocated? I am aware that if I ask ownership of an object I have to release it at a certain point, but what if I just want the object's pointer to be null at a certain point(not basing on the retaincount)? Should I call dealloc directly? I find sometimes very confusing to keep under control the retain/release mechanism.
If someone could give me a quick breakdown to make my mind 'click', i would be extremely grateful.
Thanks.
The short answer is you shouldn't worry about when an object gets deallocated (unless you are debugging a memory management problem). You should just worry about ensuring that if your code retains, copies or inits an object, it releases or autoreleases it. By doing so you will ensure reference counts are properly maintained and hence deallocation will be managed for you.
Leave the task of deciding when to dealloc an object to the runtime. Never call dealloc directly unless you are calling the super classes dealloc method at the end of your objects dealloc method.
Also, don't even look at the retain count property of an object. Various pieces of the framework manipulate those too during the lifetime of the object, and you'll see that number move around seemingly at random. It'll just drive you nuts.
The really important thing is to make sure you've got the objects retained that would be a problem if they went away suddenly, and released when you're okay with them going away suddenly.
aViewController=[[AViewController alloc]init];retainCount is 1
[self.window addsubview aViewController.view];retainCount is 2 (adding the view increments the retainCount)
[aViewController release];retain count decrements to 1;
[aViewController removeFromSuperView];retain count decrements to 0;
Now the dealloc method will be called the allocated memory will be freed. This is what have understood please correct me if i am wrong i always find difficulties during memory management.

Should I release an UIImageView added to my view if I will detect touch on it later on?

I've learnt that if you create an object, you own it and need to release it when you're done with it. In this case I create an UIImageView and add it to my view like this:
myImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"image.png"]];
[myImageView setFrame:CGRectMake(10,10,100,100)];
[self.view addSubview:myImageView];
[myImageView release];
If I later on want to detect touch on myImageView like this in my touchEnded-method:
if([touch view] == myImageView){
NSLog(#"TOUCHED!");
}
This works, but is this correct, since I now used myImageView after releasing it?
And how do I release myImageView from the self.view that I added it to earlier?
The cardinal rule of Cocoa memory management is that you should retain those things you care about, and release those things you do not care about. There are a very small number of exceptions to prevent retain loops (delegates and datasources are never retained), but this is the rule you should follow.
In this case, if you are storing the image in an ivar, I would continue to retain it, regardless of the fact that its superview will always retain it, and so you don't "have" to. But if the view is removed from its superview, you will wind up with a dangling pointer, and then you will crash, so I code defensively against that by retaining. If you used an accessor here (which you should), then this would be automatic and much safer.
Apple has grown more consistent about this in iOS, switching their recommendation about IBOutlets. On Mac, you do not retain your IBOutlets, but in iOS, Apple explicitly instructs you to do so. This is similar to the situation you are discussing, and I agree with Apple's move towards a safer approach.
As long as your myUIImageView object has a retain count > 0, it will still exist and you can continue using it. When you first add it as a subview, it gets a retain message so it's retain count is likely 2. Then you send it release, so its retain count is reduced to 1. This means it still exists in memory. Now, if you sent it release again, or sent it removeFromSuperView then its retain count would be zero, and you'd lose it.
The behavior is erratic, sometimes you may see it works, sometimes you get a crash.
If you want to use that variable to point to your image view, retain the ivar (by using a retain property). This way you ensure that the image view is available for your controller class to use.
Assuming myUIImageView is an ivar of your custom UIView subclass, your code will work as long as your image view stays in his superview. The image view instance may be deallocated and you may end with an invalid pointer referencing a deallocated object. At best you crash.
According to memory management guidelines, you should consider your image view <-> custom uiview subclass relation as wether:
strong reference. You own the image view (as you created it), and are responsible for retaining / releasing it
weak reference. You don't own the object, thus keeping a reference to it may be dangerous.
in your case, it's probably a strong reference. your myUIImageView ivar should be a nonatomic retained property of your object.
If you need to access your UIImage at some point in the future, you need to retain it.
How you do this is at your discretion, but you should not rely on the UIView to retrain your objects for you. The situation you've created works for now, but it's fragile.

How can i see if dealloc is being called on a uikit object, or any object not created by myself

I think i have an UIImage that has a higher retain count than it should have and i am probably leaking memory. I use this image as a thumbnail, to set a custom background to a uibutton. So the uibutton is holding a reference to it and so do i. But instead of 2, the retainCount is 3. Do i have to create a custom UIImage derived class and override dealloc if I want to place a log message there and then change the class used from UIImage to my class, or is there an easier way. Thanks in advance.
Use a category on the targeted class to override dealloc and set a breakpoint on it.
http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocCategories.html
Do you know the object is leaking? It's pretty much always a bad idea to leap to conclusions based on retain counts. Use Build & Analyze, Leaks and so on to determine if you've a problem.
If you really want to subclass and log dealloc, you can, but what is it actually going to tell you?
I would suggest you use the "Leaks" tool in Instruments. It will tell you if you have a leak or not and give you all the information you need.
Update:
I've just been watching a WWDC 2010 video "Future Proofing your Application" where the Apple engineer states that on OS 2.x [UIImage imageNamed:] actually leaks with a retain count 1 more than it should be. So if your device is running iPhone OS 2.x then that would be why!

iPhone Development - Release an autoreleased object

What happens if I release an autoreleased object? Its an autoreleased UIButton I want to release and the only way to create a UIButton is to use the convinience method buttonWithType:. Will it be released from memory like a normal object? Or should I just let the autoreleasepool take care of it? I wouldn't have made it autoreleased in the first place if I could.
Thanks!!
You should just let the autorelease pool take care of it. Once you add your button to a parent view, that view will retain it, and the autoreleased handle will get taken care of by the autorelease pool.
The easiest way to think of it is in terms of ownership—you don't "own" the reference you got via a convenience method, so you don't need to bother releasing it unless you retain it as well.
You must only release an object which you own. +buttonWithType: does not return an owned object, so you must not release it.
Review the Cocoa Object Ownership Rules.
Why are you trying to avoid an autoreleased object here? Presumably you are creating the button because you are using the button and inserting it into a view hierarchy, so there is no real reason to accelerate the draining of the autorelease pool which contains the button.

Cannot allocate new instance of UIView subclass after deallocating

I have an instance variable *TangramLevel(:UIView) currentLevel; in my viewController class, and I have an instance allocated at start (it's retainCount 1). I attached it to the view [self.view addSubview:currentLevel]; (retainCount 2).
When the level finishes, it notifies the controller, so controller removes it from the view [currentLevel removeFromSuperview]; (retainCount 1), and release the allocated instance - [currentLevel release]; -, to have it deallocated (retainCount 0 = invoke dealloc).
Then on the next line, controller wants to allocate/addSubview a new level instance with another level data, but the application crashes (EXEC BAD ACCESS).
If I don't release currentLevel after removeFromSuperview, the appliaction works, but I have an unused level instance left in memory then, which is also a problem (the main problem itself).
Is there any bug in the method I wrote above? Or the bug is elsewhere, maybe in the level class? I allocated some UIImageView in the level, but I release every allocated object in the levels dealloc method. Any ideas?
Post your code.
This is definitely a memory management issue. The question is "where is the problem created?" To answer that, we need to examine the following:
Your "currentLevel" iVar handling code (do you used synthesized properties, etc.). Post it.
How are you assigning the view to currentLevel?
Where are you releasing this, specifically?
How is your view's dealloc implemented (what do you release and how)?
Is there any other code that retains/releases this view or anything related to it?
The fact that you're calling release in your "I'm done with this level, let's swap in the next" code suggests an overall design issue. Make the memory management of each of a class's iVars the responsibility of its accessors and ONLY use the accessors to interact with it (even from within the class/instance). With synthesized properties, this makes it brain-dead-simple. That way you don't have to worry about where to retain/release iVars because it's always funneled through the accessors.