Search code examples
iphoneipadxcode4.2storyboard

Xcode 4.2 & Storyboard, how to pass data between views? Existing code error


I'm trying to learn how to pass data between views. Say set a label in the second view from text entered into a text field on the first view. I basically have tried making a string in the second view and then when switching from the first view to the second I set a string in the second view. Then when the second view loads its sets the text of a label to the same string. I NSLog right before and after the transition, before its fine, but when the second view loads it string gets erased. I'm not sure why this isn't working. Here is my project: http://www.mediafire.com/?83s88z5d06hhqb5

Thanks!

-Shredder2794


Solution

  • StoryBoards are ready made things where you can reduce a lot of code you write.So consider controller A & B on storyboard. Now for passing data From A to B you can connect them with a segue name its identifier and then you can use delegate methods in A as:

    //This method gets called before transition from A to B.

    - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
    {
    
        if ([[segue identifier] isEqualToString:@"THE IDENTIFIER YOU NAMED"])
        {
    
            id *objectOfController_B  = [segue destinationViewController];.
            objectOfController_B.lblTextDisplayOfA = //Something...
        }
    }
    

    Now You can Explicitly transition it by using button in controller A.

    - (IBAction)buttonPressed:(id)sender
    {
        [self performSegueWithIdentifier:@"THE IDENTIFIER YOU NAMED" sender:sender];
    }
    

    So I guess you can try experimenting on this and you will get it how and when transition occurs with segue.

    Hope this helps.