chrizonline
chrizonline

Reputation: 4979

iOS - pass data to another view controller

i have two view controllers, lets call them firstViewController and secondViewController. they are linked from firstViewController to secondViewController using segue in storyboard. the storyboard segue properties are:

identifier: showSecondViewController
style: moda

firstViewController contains collectionViews of product items and a label showing the total number of items in shopping cart. When a collectionView item is clicked, it will open up secondViewController. on secondViewController, i click add button to add items into shopping cart. when this happens, i wanna update the label showing the total number of items in shopping cart in firstViewController.

how shall i do this? should i create another segue between secondVieController and firstViewController?

i tried the following but am getting error: No visible @interface for "secondViewController declares the selector 'pushViewController:animated'

-(IBAction)addToCart:(id)sender
{
......
    firstViewController *fvc = [[firstViewController alloc] init];
    fvc.badge.value = _shoppingItems.count;
    [self pushViewController:fvc animated:YES];
}

Upvotes: 0

Views: 158

Answers (2)

kkumpavat
kkumpavat

Reputation: 452

According to code your code, you are calling pushViewController:animated: on self in -(IBAction)addToCart:(id)sender. But pushViewController:animated: is method of UINavigationController not UIViewController. So you should change your function as below.

-(IBAction)addToCart:(id)sender
{
......
    firstViewController *fvc = [[firstViewController alloc] init];
    fvc.badge.value = _shoppingItems.count;
    [self.navigationController pushViewController:fvc animated:YES];
}

Upvotes: 0

Paulw11
Paulw11

Reputation: 115002

You should familiarise yourself with the Model-View-Controller architectural pattern as this is the most commonly used pattern in user-interactive applications. You have your views, which are in your storyboard, your controllers (UIViewController subclasses), what you are probably missing is your model - This is a class that stores and manages the data - in your case this is your shopping cart.

I would suggest that you create a ShoppingCart class and implement it as a singleton that way any of your view controllers can easily get a reference to it.

As far as returning to your first view controller from your second, you can use an unwind segue - See the second answer to this question, not the accepted answer.

The code in your question is attempting to present a new instance of view controller 1 - which, if it worked, would result in a deeper and deeper series of views as your app was used.

Upvotes: 1

Related Questions