Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass data back from one view to other View in IOS?

I am able to pass data from one view to other view without any problem. But here is my situation i am facing problem.

Let's say -> Passing data to other view

ViewA->ViewB This working perfectly fine 
ViewB->ViewC This working perfectly fine
ViewC->ViewB Here is the problem.

I tried using push segue ,it goes to ViewB but when i press back button it goes to ViewC->back button->ViewB->back button->View A. From ViewB when i press back button it must goes to ViewA.

Tried using modal segue, it goes to ViewB but then i can't go any where.

As i am new to iOs I am really haven't got any idea about how to achieve this?

How to pass data back to ViewB from ViewC?

I think you guys can help me.

Edit

In View A i am calling ViewB like this

-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([segue.identifier isEqualToString:@"RemixScreen"])
{

    if([self.recipeFrom isEqualToString:@"ViewB"])
    {

        ViewB *reciepe = [segue destinationViewController];
        //somedata i will pass here

    }  
}
 }

In View B i am calling like this

-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  {
if([segue.identifier isEqualToString:@"ViewA"])
{  
    ViewA *data = [segue destinationViewController];
    //some data  
}
}

Thanks for your help guys.

like image 760
vinothp Avatar asked Dec 03 '22 02:12

vinothp


1 Answers

The correct way to do this is to use delegates. You use properties in prepareForSegue to pass data forward and delegates to pass data back.

The way it works is to have a delegate property in ViewC that is set by ViewB in prepareForSegue. That way ViewC can communicate with ViewB via a protocol you set up.

EDIT: Adding code to demonstrate:

ViewControllerBInterface:

@protocol ViewBProtocol

- (void)setData:(NSData *)data;

@end

@interface ViewBController: UIViewController <ViewBProtocol>
...
@end

Here we make ViewBController follow our protocol that ViewCController will communicate to.

Next up is ViewCController interface:

@interface ViewCController: UIViewController

@property (nonatomic, weak) id<ViewBProtocol> delegate;

...

@end

Now we look at ViewBController's prepareForSegue:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    UIViewController* controller = [segue destinationViewController];
    if ([controller isKindOfClass:[ViewCController class]])
    {
        ViewCController* viewCController = (ViewCController *)controller;
        viewCController.delegate = self;
    }
}

As you can see we link the ViewC controller to the ViewB one via the delegate property. Now we do something in ViewC:

- (void)sendData:(NSData *)data
{
    [self.delegate setData:data];
}

And you can use that in your viewWillDisappear method of ViewCController if you wanted to.

like image 178
Cthutu Avatar answered Dec 11 '22 11:12

Cthutu