将值从控制器传递给控制器

时间:2014-10-10 18:05:41

标签: ios objective-c

我正在构建我的第一个iOS应用程序来尝试学习iOS编码。但是,我需要将值xAuthToken从一个控制器传递给另一个控制器。我似乎无法让它发挥作用。我在第一个控制器ViewController中初始化值,但我在SettingsController中需要它。我不断收到错误,它现在抛出的错误是:Property 'ViewController' not found on object of type 'ViewController'

我做错了什么?

ViewController.h

#import <UIKit/UIKit.h>
#import "SettingsController.h"

@interface ViewController : UIViewController <UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *txtUsername;
@property (weak, nonatomic) IBOutlet UITextField *txtPassword;

- (IBAction)sigininClicked:(id)sender;

- (IBAction)backgroundTap:(id)sender;
@end

ViewController.m

#import "ViewController.h"

@interface ViewController ()

@property (nonatomic) NSString *xAuthToken;

@end

@implementation ViewController

- (IBAction)sigininClicked:(id)sender {

    NSString *xAuthToken = @"0";

    self.viewController = [[SettingsController alloc] init];
    self.viewController.xAuthToken = xAuthToken;
    [self performSegueWithIdentifier:@"login_success" sender:self];

}

SettingsController.h

#import <Foundation/Foundation.h>

@interface SettingsController : UIViewController

@end

SettingsController.m

@interface SettingsController ()

@property (weak, nonatomic) IBOutlet UITextField *myTextField;
@property (weak, nonatomic) IBOutlet UISwitch *mySwitch;

@end

@implementation SettingsController

//THIS IS WHERE I NEED XAUTHTOKEN

3 个答案:

答案 0 :(得分:2)

如果您有一个显示SettingsController的segue,请在prepareForSegue中传递所需的信息。不要创建新的本地SettingsController

答案 1 :(得分:0)

您可以执行类似

的操作
viewController = [self.storyboard instantiateviewcontrollerwithidentifier:@"your vc name"];
viewController.Xauthtoken = data;
// Do something else with this.

或者另一种方式(我不知道它是好还是坏,在你的vc已经激活时使用它): 使用NSNotificationCenter并在它之间传递值。

第三种方法是为第一个Viewcontroller创建委托。

答案 2 :(得分:0)

在ViewController.m中尝试:

#import "ViewController.h"

@interface ViewController ()

@property (nonatomic) NSString *xAuthToken;

@end

@implementation ViewController

- (IBAction)sigininClicked:(id)sender {
    xAuthToken = @"Your Value Here";
    [self performSegueWithIdentifier:@"login_success" sender:self];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
   if ([segue.identifier isEqualToString:@"login_success"]) {
       SettingsController *destViewController = segue.destinationViewController;
       destViewController.xAuthToken = xAuthToken;
   }
}

在您的SettingsController.h

#import <Foundation/Foundation.h>

@interface SettingsController : UIViewController

@property (nonatomic,strong) NSString *xAuthToken;

@end

SettingsController.m

@interface SettingsController ()

@property (weak, nonatomic) IBOutlet UITextField *myTextField;
@property (weak, nonatomic) IBOutlet UISwitch *mySwitch;

@end

@implementation SettingsController

-(void)viewDidLoad{
    NSLog("%@",xAuthToken);
}