Passing data between view controllers - iOS Xcode - what's a good way?

前提是你 提交于 2019-12-09 08:21:26

Since you're using Storyboards, it makes more sense to be using Segues to perform the transition between your ViewControllers. If you're not familiar with segues you can have a look here:

http://developer.apple.com/library/IOs/#featuredarticles/ViewControllerPGforiPhoneOS/CreatingCustomSegues/CreatingCustomSegues.html

It's very simple to create a segue in IB. Once you have that set up you implement
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender and configure your destination view controller. So you'll have something like the following.

-(void)prepareForSegue(UIStoryboardSegue *)segue sender:(id)sender{
    // Assume you have a viewHomeSegue defined that has the name of the segue you want to perform
    NSString * segueIdentifier = [segue identifier];
    if([segueIdentifier isEqualToString:viewHomeSegue]){
        ViewControllerHome * homeController = (ViewControllerHome *)[segue destinationViewController];
        homeController.lblUSERNAME.text = _textFieldUsername.text;
    }
}

You shouldn't keep strong references between those two ViewControllers in both directions. What you can do, for example, is to declare a protocol in your ViewControllerWelcome with a delegate in it. You could let the ViewControllerHome instanciate the other controller and then be its delegate which gets informed as soon as the user finished entering the username.

@protocol ViewControllerWelcomeDelegate <NSObject>    
- (void) userNameEntered:(NSString *)userName;    
@end

@interface ViewControllerWelcome : UIViewController
@property (nonatomic, weak) id <ViewControllerWelcomeDelegate> delegate;
...
@end

In your @implementation:

- (BOOL)textFieldShouldReturn:(UITextField *)theTextField
{
   [theTextField resignFirstResponder];
   [delegate userNameEntered:theTextField.text];

   return YES;
}

if you have a .storyboard file you can layout your views in there like with interface builder.

This documents really helped me out the first time:

Part 1: http://www.raywenderlich.com/5138/beginning-storyboards-in-ios-5-part-1

Part 2: http://www.raywenderlich.com/5191/beginning-storyboards-in-ios-5-part-2

If you only want to check out the segues part, I'd recommend you to read part 2 only.

ipatch

I refined this question with another question on SO that can be found here Basically, I created a singleton to pass the data between the view controllers. I haven't had any problems with it so far (knocks on wood).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!