"[CALayer release]: message sent to deallocated instance" when dismissing modal view controller - iphone

I've been struggling with this for last few days and I cannot find any solution, so I ask you for advice.
I have two UIViewControllers: NewPostUIViewController and SettingsUIViewController. In the second one I have a field:
id<SettingsUIViewControllerDelegate> delegate
and the first one implements protocol
SettingsUIViewControllerDelegate
When a button is pressed the following code is executed in NewPostUIViewController:
SettingsUIViewController *settingsUIViewController = [[SettingsUIViewController alloc] initWithNibName:#"SettingsView" bundle:nil];
settingsUIViewController.title = NSLocalizedString(#"Settings", #"Settings view title");
settingsUIViewController.delegate = self;
[self presentModalViewController:settingsUIViewController animated:YES];
[settingsUIViewController release];
when I want to dismiss SettingsUIViewController I call (code in SettingsUIViewController):
[delegate settingsAreDone:sender];
and settingsAreDone looks following (code in NewPostUIViewController):
[self dismissModalViewControllerAnimated:YES];
This all concludes in:
[CALayer release]: message sent to deallocated instance 0x5a76840
I tried to debug the code by setting a breakpoint in the release methods of both view controllers, but these methods are called so often that it's hard to say what can be the cause of this problem.
Any ideas?

First, the error you're getting isn't indicating that -release is being sent to a view controller, so breakpoints in your view controllers won't help. The over-release is happening on a CALayer, which is likely part of the modal animation.
First, we start with some basics about the delegate. I don't feel great about this being the cause, but you should always start with the easy basics. Your SettingsUIViewController delegate property should be assign, not retain, so you avoid retain loops. That's probably correct already, but when it's not, you can wind up with cases where objects exist longer than you expect them to (and so can send messages after their targets have gone away). Again, probably not the issue, but easy to check and easy to fix.
Next, you should look at the stack trace at the crash. Who is calling [CALayer release]? A possible cause is that the owning view controller gets released before the animation stops. When you close the settings controller, do you immediately close the NewPost controller?

Related

Modal View doesn't release itself after dismiss

I've been facing a weird issue with dismissing a modal view.
I present a modal view like this:
ResepiDetail *detail =(ResepiDetail*)[[ResepiDetail alloc]init];
[self presentModalViewController:detail animated:YES];
and dismiss it like this with a back button:
[self dismissModalViewControllerAnimated:YES];
after this the view dismisses itself and goes back to the previous view, but it doesn't release itself from memory. I found it out by sending a notification message and that view received it. Additionally I tried to track the VM memory Allocation, and it seems the view is still in memory.
I'm using ARC and have the same method used for another view which works perfectly.
The code is fine, as posted, so here's some hints on how to proceed:
A sure fire way to be certain your view controller hasn't been deallocated is to override dealloc and log something identifiable. You can still do that in ARC, just don't explicitly call super. If you don't see the log when you expect to, then you have a problem.
Assuming that you have determined that you absolutely do have a problem, then the issue becomes finding the retain cycle. If the issue is that an instance of ResepiController isn't being dealloc'd, then you need to look for...
Any code outside the ResepiController class that has a strong reference to it. For example, if your class signs up as the delegate of some other class, make sure the delegate isn't using a strong reference.
Any internal blocks that may have implicitly retained self. Are there any blocks anywhere in your program that may have a reference to your controller at the time that you think it should be released?

[Not A Type release]: message sent to deallocated instance 0x5853f00

[Not A Type release]: message sent to deallocated instance 0x5853f00 getting this error please help when adding a view
AnotherView* obj = [[AnotherView alloc] init];
[self.view addSubview:obj.view];
[obj release];
You are adding [UIView view] to the current view. There is no view property inside UIView.
As pointed out, you should add the UIView object itself.
In an OpenGL context, you should also consider what the docs say:
Note: If you are using OpenGL ES to do your drawing, your view’s drawRect: method is not called. Instead, it is up to you to determine when your view needs to be redrawn and initiate the appropriate drawing updates.
So make sure your UIVIew is initialized correctly.
You generally get this error when you send a message to already released instance. So what I suspect in your code is, you created some views and then you added it to some other view and released the previous created view. Now if any action performed on the first view (which is already released) will cause the exception.
i.e.: First View contains a button and action for this button's touchup inside is written in FristViewController. Now I created the instance of FirstView and added into second view and released the firstview instance. Now suppose user tap on FirstView's button then, iOS will search for controller (FirstViewController) which is already released, and this problem will occur.
To get rid of the problem you can simply send autorelease message to the instance and will work fine.
The main reason of this happening is, addSubview does not take care of retain count.
I hope this will help you.
You can't release obj because [self.view addSubview:obj.view] only add view of obj not entire object.
If you release it and your view is visible on screen then it may possible that some message will be sent to deallocated object, so it result in crash.

Preventing bad access crash for popViewControllerAnimated in uinavigationcontroller setup

So, under low memory, my root view is unloaded. That's expected and accounted for. However, how do I deal with modal/pushed view controllers who need to be popped, since they reference the main navigationController? I have a custom Done button in a pushed view controller, which calls [self.navigationController popViewControllerAnimated:YES]. If the root view has been unloaded, this gives a bad access error. Is there a better way to do this?
My setup is
AppDelegate has a NavigationController
this NavigationController has a view controller MainViewController
//MainViewController.m
- (IBAction)showAnotherController:(id)sender
{
AnotherViewController * anotherViewController;
anotherViewController = [[AnotherViewController alloc] initWithNibName:#"AnotherView" bundle:nil];
[self.navigationController pushViewController:anotherViewController animated:YES];
[anotherViewController release];
}
//...Here I can simulate a memory warning to force unloading of MainViewController's view
//in AnotherViewController.m, called from a custom toolbar item
- (IBAction)done:(id)sender
{
[self.navigationController popViewControllerAnimated:YES]; // bad access here, looks like self.navigationController is no longer available. Am I doing this wrong?
}
The scenario you're describing does not cause bad access. However, if you don't handle the described scenario carefully you get bad access. Since you haven't showed me any code I can't tell you that this is the problem you're having, but it's a very common problem.
When you receive a memory warning and your view is unloaded, you probably release a bunch of stuff. In addition to releasing the variables you also have to set them to nil. If you don't, you're facing the risk of sending messages to released objects, which causes bad access.
Again, I can't know that this is your problem, but it's usually the problem.
EDIT: Since you seem to believe that self.navigationController doesn't exist (it probably does) I'm gonna tell you about something called NSZombie:
NSZombie will tell you what released object is being sent a message (aka EXC_BAD_ACCESS). This is a very useful tool when you get EXC_BAD_ACCESS, so learn how to use it.
To activate NSZombie do the following:
Get info of the executable.
Go to the arguments tab.
In the "Variables to be set in the environment:" section add:
Name: NSZombieEnabled
Value: YES
Then run your app as usual and when it crashes it should tell you which deallocated object received the message.

iOS Development: Why are the retain counts for my view controller so strange?

I'm diving into iOS development and I'm building a navigation based app that wasn't fully releasing one of the views that was being pushed onto the nav stack. This is problematic because the view controller is never being deallocated, so the memory it uses just builds up every time the view controller is pushed on to the stack. So after investigating the issue, I found the retain counts for the view controller were really strange. The view controller in question is pushed on to the stack once a countdown timer reaches zero.
Here's the code that creates the view controller in the timer callback, displays its retain count, and pushes it onto the nav stack...
-(void)updateCountDownTimer //Defined in MyViewController_A class
{
[self setTimeRemaining:([self timeRemaining] - 1)];
[[self countDownLabel] setAlpha:1];
[[self countDownLabel] setText:[NSString stringWithFormat:#"%d", [self timeRemaining]]];
//Fade out the current time
[UIView beginAnimations:#"FadeAnimation" context:nil];
[UIView setAnimationDuration:1];
[[self countDownLabel] setAlpha:0];
[UIView commitAnimations];
if ([self timeRemaining] == 0)
{
MyViewController_B *myvc_b = [[MyViewController_B alloc] initWithNibName:#"MyView_B_iPhone" bundle:nil];
[[self navigationController] pushViewController:myvc_b animated:YES];
NSLog(#"updateCountDownTimer: %d", [myvc_b retainCount]);
[myvc_b release];
[[self countDownTimer] invalidate];
[[self countDownLabel] setHidden:YES];
}
}
and here's the code that pops the view controller off the nav stack once the pause button is pressed...
- (void)pauseButtonPressed:(id)sender
{
//Stop the timer
[puzzleTimer invalidate];
NSLog(#"pauseButtonPressed before pop: %d", [self retainCount]);
//return to the previous view
[[self navigationController] popViewControllerAnimated:YES];
NSLog(#"pauseButtonPressed after pop: %d", [self retainCount]);
}
and here's the console output that shows really strange retain counts throughout the process...
2010-12-02 17:50:38.062 MyApp[821:307] updateCountDownTimer: 5
2010-12-02 17:50:40.453 MyApp[821:307] pauseButtonPressed before pop: 2
2010-12-02 17:50:40.462 MyApp[821:307] pauseButtonPressed after pop: 4
I'm new to iOS development, but the code seems pretty straightforward to me, so I don't know what I'm missing.
Thanks so much in advance for your wisdom!
UPDATE: It looks like the Leaks instrument is reporting a leak on the line of code that pushes the previous view controller onto the stack (that is, the view controller responsible for pushing the view controller in question). The code is once again very straightforward, so I don't know why it's reporting a leak...
MyViewController_A *myvc_a = [[MyViewController_A alloc] initWithNibName:#"MyView_A_iPhone" bundle:nil];
[[self navigationController] pushViewController:myvc_a animated:YES]; //<--Leak being reported here
[myvc_a release];
*UPDATE:*Found the problem, it was just as everyone was saying and the same problem as was shown in the link posted in the comments below, I had live objects still referencing my view controller, which prevented it from deallocating. In my case, I had two timers that were targeting my view controller and those timers weren't being invalidated before I popped the view off the stack, which meant there were two live objects still referencing the view controller. Here's a snippet I found in the Apple docs which uncovered the problem...
Perhaps more importantly, a timer also
maintains a strong reference to its
target. This means that as long as a
timer remains valid (and you otherwise
properly abide by memory management
rules), its target will not be
deallocated.
Anyhow, thanks again to everyone who helped!
You're not missing anything -- instances of UINavigationController just do strange, strange things to the retain count internally.
You should only worry about the retainCount if you see a specific memory leak that you're trying to patch up. In this case, of course, you DO have a problem... the retainCount just doesn't help, since it's so bizarre.
You might check if dealloc is getting called on MyViewController when you do the pop. Also, before you test, comment out the lines that check the retainCount. Calling retainCount will sometimes add to the retainCount.
To really nail down what's going on, in Xcode, go to the Run menu, and select Run With Performance Tool > Leaks. Push and pop that view controller, and you should see it pop up as a leak. You'll be able to see all of the retain and release calls on the object.
If you're really stuck, Apple's guide to Finding Leaks has a few more clever solutions. Good luck!
There is nothing wrong with your code as far as memory management is concerned.
You should not rely on retain counts to check if your objects are being released properly as the system will also be retaining what it needs and releasing when appropriate. For instance when you add your view controller to the stack it gets retained by the nav controller along with its subviews and when it's popped out it gets send a release message which propagates all of its subviews.
The general rule is if you alloc, retain or copy an object, it is your responsibility to release it. Everything else is dealt with by the system and will be flushed with the auto release pool.
Never, ever, ever look at the retain counts of your objects. They should not be used programmatically, and are misleading when you are trying to debug your code.
Here's why: You know that in your code, you are making calls to retain and release to manage your retain count. But you may also be making calls to -autorelease, which causes your retain count to be decremented at a later date over which you have little or no control. Worse, any time you pass a reference to your object to an object that you do not control the implementation of (which is likely to happen to most of the objects you create), the receiving object may make its own adjustments to the retain count - and that object may pass your object to yet other objects, which also adjust the retain count.
The point is, you should not ever look at the retain count of your objects for any reason at any time. They will only serve to confuse you. Your job is to manage your own claims to an object correctly, and trust that the code written by others is doing so as well.

how to know whether dealloc is getting called or not in iphone sdk?

i am using UIviewcontroller subclasses. In my main view i have 3 buttons, each button will load a different nib. and each new nib is having one back button to come back to main view.
when i click one the back button of any view to move to the main view the dealloc of that view is not getting called? i didnt understood this.
can anyone explain when those views dealloc will be called?
if the dealloc method hasn't been called, it means that your retained your viewController object by hands. for example, in this case dealloc will not be called after clicking back button to return
MyViewController *controller = [[MyViewController alloc] init];
[self.navigationController pushViewController:controller animated:YES];
You should add
[controller release];
to this code to be sure that your instance of viewController will be deallocated. If you are absolutely sure, that you had sent equal number of alloc(or any message that increases object's retainCount) and release messages for your object and dealloc method doesn't be called anyway, it will be more complex. I hope that this answer will help. If you will find that your situation is "more complex", post a comment, then I'll try to explain with more details.
I too would like to dive deeper into understanding memory management details (below surface level) where it comes to controllers being pushed on and off of the stack. I built my framework from the text, "Beginning iPhone 3 Development" by Mark and LaMarche, but that text effectively re-uses sub-controllers and their dealloc methods never get called.
I have noticed that repeated use of a sub-controller with a NIB containing a UIWebView that calls Google's web directions url ... eventually results in a memory warning and my data is lost. This involves repeated "reuse" of the sub-controller.
If you can point me as well to in depth text that goes into nav controller and sub view memory management, that would be excellent.