Some memory management understanding - iphone

I have created a property of a viewController and retaining it from ClassB of viewController (Class A).
so basically I have #property (nonatomic, retain) ClassAViewControllerVC, and synthesized in the main file.
I have an IBAction in which I am allocating ClassAViewController and pushing it on navigation stack, but I am trying to analyze where should I release this viewController?
- (IBAction) response {
ClassAViewControllerVC = [ClassAViewController alloc] initWithNib:#"ClassAViewController" bundle:[NSBundle mainBundle]];
[self.navigationController pushViewController:self.ClassAViewControllerVC animated:YES]
}
Is it okay to release the view controller after I stack it on the navigation-Controller as described above?
Also, is it a good idea to set property for such viewController at the first place? I started to notice that my apps started to crash if not utilized #property retain way. Any thoughts or concern would be appreciated.
Thanks

Firstly, no, it's not necessary to keep such an object in a property. You only need to keep objects in a property if the class will require access to the object later on. In this case, I think a local variable will do.
In this example, you create a ClassAViewController with alloc, meaning that the caller (this method) has responsibility to release it once it's finished with it.
When you add it to the navigation controller stack, the navigation controller retains it, because it keeps a reference to it.
So, at the end of this method, you should release it, but it's been retained by the navigation controller, so it's not deleted.
The code should look like this:
- (IBAction) response {
ClassAViewController *viewController = [ClassAViewController alloc] initWithNib:#"ClassAViewController"
bundle:[NSBundle mainBundle]];
[self.navigationController pushViewController:viewController animated:YES]
[viewController release];
}
P.S. it's convention in objective-C to write variable names starting with a lowercase letter. Uppercase starting letters are used for class names, and it confuses the bejeesus out of me! ;)

if ClassAViewControllerVC is a field of ClassB, you should release it in the dealloc method.
But you should probably create ClassAViewControllerVC in the init or even better viewDidLoad method.(note: if you create something in viewDidLoad, you need to release it viewDidUnload as well, not only in dealloc)
Because now every time "response" method is called ClassAViewControllerVC will be created all over again. (and there is not much sense storing it in the property). If this is what you want you probably should not make ClassAViewControllerVC a filed of your ClassB, but just have it as s local variable in response method like this:
- (IBAction) response {
ClassAViewController *classAViewController = [ClassAViewController alloc] initWithNib:#"ClassAViewController" bundle:[NSBundle mainBundle]];
[self.navigationController pushViewController:classAViewController animated:YES];
[classAViewController release];
}

Best way to solve this problem is, drag and drop empty UIViewController in your ClassB.xib file. Create #property (nonatomic, retain) ClassAViewControllerVC, make the connection to empty UIViewController you just drop to classB.xib file and also change the NIB name to the class A nib file name. This will solve all the problem of crashing because you are not allocating or releasing any memory.

Related

Does a subview viewcontroller added via addSubiew need a dealloc?

normally when I'm using a viewcontroller that will push the current viewcontroller out of the way, I use a UINavigationController and push/pop the new viewcontrollers and let them handle all the dealloc themselves.
However, for example, in this case, I have a MainViewController, which is the default view when the app starts up. I have a second view, called SecondaryViewController, that is a popup on the main screen (sort of like a lightbox).
Here is the code to illustrate:
//From within mainViewController:
secondaryViewController = [SecondaryViewController alloc] initWithNibName:#"SecondaryViewController" bundle:nil];
[self.view addSubview:secondaryViewController.view];
The secondaryViewController interface looks like this:
//interface
#interface SecondaryViewController : UIViewController
{
IBOutlet UILabel *httpLabel;
IBOutlet UIScrollView *scrollView;
}
#property(retain, nonatomic) IBOutlet UILabel *httpLabel;
#property(retain, nonatomic) IBOutlet UIScrollView *scrollView;
As for the implementation, I have the #synthesize for the #property ivars, but I'm not doing any manual allocs. However, I did put a dealloc method:
- (void)dealloc
{
[httpLabel release];
[scrollView release];
[super dealloc];
}
But I'm not sure I need the above.
So my questions would be the following:
1) Do I need the above dealloc method in this case? Or more generally, when would a subview need a dealloc method?
2) If I do or dont need it, does it depend on whether I'm adding the secondaryViewController via addSubview or pushViewController? For instance, if I wanted to replace the entire mainViewController, with this:
[self.navigationController pushViewController:secondaryViewController animated:NO]
Would the secondaryViewController need a dealloc method?
Thank you!
Yes, you do need the dealloc method exactly as you have it, in this case. You are on the right track because you're assuming that since you are not doing any manual allocating, you don't need to do any dealloc/releasing... however, by specifying the property as (retain, nonatomic), you are doing implicit retaining.
This means that if you ever set those properties, what's actually occurring under the covers is something like this:
-(void)setHttpLabel:(UILabel *)newlabel
{
if (newLabel != httpLabel)
{
[httpLabel release];
httpLabel = [newLabel retain];
}
}
As you can see, your synthesize is causing a retain to occur on an object. If you never balance that retain out with a release, it will leak. So the only logical place to put it, is in your dealloc method. This creates the circle of life.
If you never set these properties and don't have release in dealloc, then it won't leak anything, but you obviously wouldn't want to make those assumptions.
If you didn't have any retain properties or any manual allocing of ivars, then and only then, can you nuke the dealloc method.
Hope that helps.
I think this is allowed in the latest iOS 5+ but previously you were not supposed to add another viewcontrollers view to your main viewcontroller. This is clear misuse and can lead to issues.
The concept of viewcontroller is one who controls all the views. A view controller should not control another viewcontroller unless it is a container viewcontroller such as UINavigationController/UITabBarController.
So please rethink the design. why do you need the SecondaryViewController. Why cannot the mainviewcontroller manage the secondary view as well?
Lastly, every viewcontroller should have the dealloc in it.
If you need to access secondaryViewController from your main view controller after you've added its view to the hierarchy, you should not deallocate it at that point. If you don't need to access the secondary controller after you've displayed it, you can dealloc it at that point.
In practical terms, if secondaryViewController is an ivar, it probably makes sense to keep a retained reference to it. If it's a local variable and you're not accessing it later, you should dealloc it.

Why a separate instance of ViewController Class is affecting previous instance?

UPDATE - Cause found!... please read below & suggest the solution:
While creating a video to show this issue, I have found why does that happen...
Any Control/Element that is defined between #imports & #implementation DetailViewController in .m file is lost by the original detVC when a new instance is created of VC.
Example:
I am including a video that re-creates this issue. As shown, all controls work except a UISegmentedControl & a UILabel.. both of which are defined in DetailViewController.m as:
#import "DetailViewController.h"
UISegmentedControl *sortcontrol;
UILabel *incrementLabel;
#implementation DetailViewController
Video Link - http://www.youtube.com/watch?v=2ABdK0LkGiA
I think we are pretty close.. Waiting for the answer!!
P.S.: I think this info is enough can lead us to the solution, but if needed I can share the code too.
EARLIER:
There's a detailViewController (detVC) in our app which is normally 'pushed' from a UITableViewController.
Now we are also implementing Push Notifications which would 'modally' present the same detVC whenever the notification arrives, which in turn can happen over any view controller.
It works all fine until the detVC through notification is presented while another instance of detVC was already the active view controller (pushed earlier through TableView).
The problem happens when the presented detVC is dismissed - the pushed detVC 'looses' control of about everything - It is not pointing to the same data as earlier & even the UISegmentedControl on Navigation Toolbar points to -1 index on pressing any index!
Why does such thing happen when we are creating a separate instance of detVC? Why does it affect the earlier detVC? How can it be resolved / What about Objective C needs to be learned here? (FYI, we are using ARC in the project)
Thanks
EDIT - Some code:
When Pushed:
ProductDetailViewController *detailViewController = [[ProductDetailViewController alloc] init];
detailViewController.hidesBottomBarWhenPushed = YES;
[self.navigationController pushViewController:detailViewController animated:YES];
detailViewController.serverOffset=serverOffset;
detailViewController.prdctIndex = indexPath.row;
When presented through Notification:
- (void)displaySingleProduct:(NSDictionary*)userInfo{
ProductDetailViewController *onePrdVC = [[ProductDetailViewController alloc] init];
UINavigationController *addNav = [[UINavigationController alloc] initWithRootViewController:onePrdVC];
onePrdVC.justOne=YES;
onePrdVC.onePrdIDtoLoad=[[[userInfo valueForKey:#"prd"] valueForKey:#"id"] intValue];
[self.navigationController presentModalViewController:addNav animated:YES];
}
There is a Product class in detVC which gets the data from the values stored at the prdctIndex row in the SQLite table.
After dismissing the presented detVC through notification, the Product class of the pushed detVC starts pointing to the row which was used for Product class in presented detVC. And there is no such code in viewDidAppear which would alter Product class.
So, this, UISegmentedControl issue mentioned above & some other problems are causing the pain! Basically, the whole detVC acts weird - which re-works if we just pop & re-push it!
EDIT 2
I have more info on it which could lead to the cause.
If I run viewDidLoad on viewDidAppear like this:
if (!justOne) {
aProduct = [allProducts getProduct:(prdctIndex+1) one:NO];
[self viewDidLoad];
[self populateDetails];
}
the pushed detVC regains the control & every element/control starts re-working as expected (but not in the ideal way). So, it is quite clear that the separate instance of presented detVC does messes up the earlier pushed detVC & a re-setting up of all the controls / pointers is required through viewDidLoad.
Can any helpful conclusion can be derived from this info?
When in your code you write:
#import "DetailViewController.h"
UISegmentedControl *sortcontrol;
UILabel *incrementLabel;
#implementation DetailViewController
You are not defining these variables as instance variables (ivars), so they are not individual for each instance. There are three ways to define ivars.
1) The traditional way, in your .h file.
#interface DetailViewController{
UISegmentedControl *sortcontrol;
UILabel *incrementLabel;
}
2) Some additions to objective-C have added support for the next two ways. Like declaring them in your .m file.
#implementation DetailViewController{
UISegmentedControl *sortcontrol;
UILabel *incrementLabel;
}
3) If these ivars use properties to expose them, then you can simply leave out the explicit definition of them. So in .h:
#interface DetailViewController
#property (strong, nonatomic) IBOutlet UISegmentedControl *sortcontrol;
#property (strong, nonatomic) IBOutlet UILabel *incrementLabel;
and then in the .m file:
#implementation DetailViewController
#synthesize sortcontrol;
#synthesize incrementLabel;
Are you loading the view controller from a NIB? If so, it may be that the same instance of the view controller is used each time. You can log the address of your view controller in viewDidLoad and see if this is the case.
It actually depends on how your apps architecture has been created. If you are using TabBarController based application, here is the proper way to do so.
If two instances of the same class are interfering with each other, that strongly suggests that you are not storing all your state in instance variables. I would suspect that something in ProductDetailViewController stores its state in global or class data, and that your problem lives in there.
It's possible that you have done something silly like making ProductDetailViewController a forced singleton (overriding +alloc, which you should almost never do), but generally people remember when they've done that.
Never call viewDidLoad directly. That's only for the system to call. (I know you were just testing, but don't leave that in.)
But are you calling [super viewDidAppear:animated] in your viewDidAppear:? You have to call your superclass in that method.

ViewController never gets deallocated

In my mind, myViewController should be deallocated around the time that I pop back to the root view controller with the following code, but I never see the deallocation message getting NSLogged.
If this should work, then what kind of problem can I look for in the myViewController's class that might cause it to get deallocated when I popToRootViewController?
Thanks.
The following gets called in my tableView:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
MyViewController *vc = [[MyViewController alloc] initWithNibName:#"MyViewController" bundle:nil];
[self.navigationController pushViewController:vc animated:YES];
[vc release];
}
UPDATE:
This code was perfect, but it was some bad memory management in my custom view controllers that caused neither to be released. I had some retained properties that should have been assign instead (or at least, that's the way I solved it). See comments for specifics.
When you use poptoviewcontroller then dealloc method will call for the topmost view controller in navigation controller. You can put a breakpoint in dealloc method of your current view controller and when you called popviewcontroller then your dealloc method gets called and release all the stuff/varaibles you have created in your view controller.
#JaySmith02 is right
it was some bad memory management in my custom view controllers that caused neither to be released. I had some retained properties that should have been assign instead (or at least, that's the way I solved it)
In my case the culprit was
#property (nonatomic, retain) id<TTSlidingPagesDataSource> dataSource;
From my viewController when I wrote
slidingPages.dataSource = self
I guess the dataSource retained my viewController and made a circular retention. The 'dealloc' of my viewController was never getting called.
Note: Under ARC dealloc does get called. Difference is you cannot call [super dealloc]
The solution:
#property (nonatomic, assign) id<TTSlidingPagesDataSource> dataSource;

Question about the mechanics of iPhone view controllers (i.e., explain why this crashes)

I am pretty new to iPhone programming, and was playing around with an app yesterday trying different scenarios with view controllers and nib files. So, I started a new app with a FirstViewController (FVC for short) and an FVC.xib.
I layed out a quick view in FVC.xib and ran the app - view displays, great.
I now wanted to have a second view I could add on top of the main view. So I went ahead and created SecondViewController.xib (SVC) but did not create the .m and .h files. I went about trying to load both these views from the same view controller, and here is where my question lies:
I created a button in FVC.xib and created an IBAction like this:
- (IBAction)loadSVC {
FirstViewController *viewController = [[FirstViewController alloc] initWithNibName:#"SecondViewController" bundle:[NSBundle mainBundle]];
secondView = viewcontroller.view;
[viewController release];
[self.view addSubView:secondView];
}
So this works great and adds the contents of SVC.xib, but when I try and remove that view from the superview, the app crashes:
[secondView removeFromSuperview];
If I actually create a view controller for SVC, use that to instantiate my view in FVC, and move the remove code to the SVC:
[self.view removeFromSuperview];
Everything works. My question - I kind of get why my first method crashes, but I was hoping someone could explain why and what goes on behind the scenes. I'm still a noob with object oriented programming, so what is actually happening in my first case where I create a new instance of FirstViewController and add its view to self.view? Why can't I release it (I assume because the original view is associated with FirstViewController, and when I create a new instance with the second xib it messes everything up) - I'd love a more technical explanation as to what is happening...
Thanks much!!
EDIT to add more info in response to Nick's reply below
Nick - so your answer did clear my thinking a bit in regards to the retain count, etc... I did another test app trying to get this working from a single view controller - think, for example, that I wanted to display an Alert or Welcome message to the user (I know in a real app there are different methods to accomplish this, but this is more of a learning experience) -- so I have my main view # MainViewController and layout my alert message in a xib called alert.xib -- so there is no logic behind the alert message, no reason for it to have a view controller that I can see, my end goal being loading/unloading this on top of my main view from the main view's view controller (or understanding why it is impossible)
I tried this using instance variables as you recommended:
In MainViewController.h:
#import <UIKit/UIKit.h>
UIViewController *secondController;
UIView *secondView;
#interface MainViewController : UIViewController {
}
#property(nonatomic, retain) UIViewController *secondController;
#property(nonatomic, retain) UIView *secondView;
- (IBAction)loadSecond;
- (IBAction)removeSecond;
#end
In MainViewController.m:
#import "MainViewController.h"
#implementation MainViewController
#synthesize secondController, secondView;
- (IBAction)loadSecond {
secondController = [[MainViewController alloc] initWithNibName:#"alert" bundle:[NSBundle mainBundle]];
secondView = secondController.view;
[self.view addSubview:secondView];
}
- (IBAction)removeSecond {
//I've tried a number of things here, like [secondView removeFromSuperview];, [self.secondView removeFromSuperview];, [secondController.view removeFromSuperview];
}
- (void)dealloc {
[secondController release];
[secondView release];
[super dealloc];
}
So - this works to load the alert view, but the removeSecond button does nothing (I did use NSLog to verify the removeSecond method is fired) - why?
Second, and most importantly - is this even possible, or is it horrible practice? Should every nib/view I am manipulating have their own view controller? Am I wrong to think I could just make a new instance of MainViewController and use it to display and remove this no-functionality, very temporary view? (And yes, I realize I could easily create this view programatically or accomplish the end goal in many different ways which would be easier, but I'm trying to really learn this stuff and I think figuring this out will help...
Thanks for the help!
You created a view controller
You accessed its view which caused controller to create the view and call the delegates (i.e. viewDidLoad)
Controller returns the view that you asked for
Now you add the view as a subview which increases its retain count
Controller is released and it releases the view, BUT since view's retain count was increased the view is still there
You try to remove the view, it is unloaded and delegates are to be called (e.g. viewDidUnload), however that messes up since the controller who created the view is released and that piece of memory is... smth else :)
That's why the first method doesn't work.
The second method is NOT correct either but it works because:
You remove controller's view from superview but since controller itself is not released (you didn't call [self release] or anything like that, not saying that you should :), just an example), then the view didn't reach 0 (zero) retain count and is still there - which means its subviews aren't removed
The proper way to do it is to save the reference to the controller as an instance variable (usually declare a synthesized property), and release it only when you are done with the view, making sure that the view is removed from superview before hand. The default templete for a View Based App shows how view controller should be managed
Hope this helps to understand why both methods behave differently
Based on your clarifications, you don't need secondView property or iVar. Also in your loadSecond instead of secontController = bla you need self.secondController = bla, otherwise you simply assign reference to the iVar instead of going through the setter.
Yes, it's possible to load subviews/other resources from a nib without having a dedicated controller
This is how you do it (one of the approaches):
UIView *result = nil;
NSArray *bundle = [[NSBundle mainBundle] loadNibNamed:#"MyNibName" owner:owner options:nil];
for ( id o in bundle ) {
if ( [o isKindOfClass:[UIView class]] ) {
result = (UIView *)o;
break;
}
}
Here the result will contain the first UIView in MyNibName. You can use other criteria to find out whether you got the view you wanted (tags, types...)

Why does releasing a view controller cause a crash?

I always push a new view controller onto the stack like this:
MyViewController *vc = [[MyViewController alloc] init];
[self.navigationController pushViewController:vc animated:YES];
[vc release];
And all works well when it comes to popping it off the stack with:
[self.navigationController popViewControllerAnimated:NO];
But now when I pop the vc off the stack I get a crash in main.m stating a bad access at line:int retVal = UIApplicationMain(argc, argv, nil, nil);
But now if I comment out [vc release] no more crash?
But why and surely this leaks memory as Im not releasing something I created?
Your memory management looks fine. Perhaps you are mismanaging the memory of something inside of your vc. What does the dealloc method of MyViewController look like?
My guess is you are using the incorrect init method (perhaps initWithNibName:bundle:) and you are releasing ivars in dealloc that were never properly initialized.
Did you try using it as a
#property
Navigation controller will retain vc then, when vc is popped, navigationController releases it and vc deallocs.
So, you must leave the release code, it is correct.
I think you have to use a initWithNibName:bundle: insted of the init.
The reason why they are different is that you are not allocating the text objects, and therefore you are not the owner. It is the IB's job to alloc and realese them, which it does.
So if you also try to release it, it will cause problems.
Perhaps you are mismanaging the memory of something inside of your vc.
This sentence from #brandontreb really helped me! I've struggled a whole day to fix the crash after a 'Received simulated memory warning', exactly descripted like:
Preventing bad access crash for popViewControllerAnimated in uinavigationcontroller setup
In my pushed view controller's loadView:, passed the view controller self to its dataSource's init:.
LayoutPickerDataSource *pickerDataSource = [[LayoutPickerDataSource alloc] initWithController:self];
while the dataSource class retained it like:
#property (nonatomic, retain) LayoutViewController *viewController;
Fix the crash just change to:
#property (nonatomic, assign) LayoutViewController *viewController;
and remove:
[viewController release];
bingo! I still don't know why! As viewController released in dealloc: of dataSource.