Model view controller when new item is created


#1

In the book we added a option when user creates a new item details of that
item are presented in a modal view controller.

code is smth like this:

[quote]

  • (IBAction)addNewItem:(id)sender
    {

    DetailViewController *detailViewController =
    [[DetailViewController alloc] initForNewItem:YES];

    [detailViewController setItem:newItem];

    UINavigationController *navController = [[UINavigationController alloc]
    initWithRootViewController:detailViewController];

    [self presentViewController:navController animated:YES completion:nil];
    }[/quote]

My question is why did we have to embed the detailViewController inside a NavigationController
before presenting the latter as a Modal view controller?

I hope I get an answer on this one, otherwise I have asked many questions here and
got too few responses. Why is that?


#2

A question I would have to ask you first is "why haven’t you try presenting the detailViewController without using the UINavigationController yourself, and see what happens :wink: ":

as you will see this view has no UINavigationBar, and therefore the user has no way of dismissing it, hence the reason it is presented inside a UINavigationController.

Nick


#3

[quote=“fujilla”]A question I would have to ask you first is "why haven’t you try presenting the detailViewController without using the UINavigationController yourself, and see what happens :wink: ":

as you will see this view has no UINavigationBar, and therefore the user has no way of dismissing it, hence the reason it is presented inside a UINavigationController.

Nick[/quote]

Actually if I do it like that, it crashes with the following exception:

2013-08-06 16:08:37.631 Homepwner[2780:c07] *** Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘Application tried to present modally an active controller <ItemsViewController: 0x914ec70>.’

Any idea why?


#4

The reason it is crashing is that the detailViewController is attached to the UINavigationController.

To make it work, just disable the statement that creates the UINavigationController and present the view controller:

- (IBAction)addNewItem:(id)sender
{
...
DetailViewController *detailViewController =
[[DetailViewController alloc] initForNewItem:YES];
[detailViewController setItem:newItem];

// UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:detailViewController];

[self presentViewController:detailViewController] animated:YES completion:nil];
}

Then it should work fine, and as Fujilla says, you should see a view without a navigation bar.

You should read the UINavigationController Class Reference.


#5

Oops, apologies for not being precise enough - I simply thought that would have been implied. :blush: