Objective-C:从另一个类访问变量

时间:2014-05-20 21:17:35

标签: ios objective-c variables

我正在创建一个项目,以便我有两个视图控制器,通过带有标识符" login_success"的模态segue连接。

在主视图控制器中,我有一个文本字段,它接受用户输入的任何内容,以及一个执行segue的按钮。

在下一个控制器中,我有一个标签,可以打印出用户输入的内容。

我的代码:

DICViewController.h(第一视图控制器):

#import <UIKit/UIKit.h>

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

- (IBAction)sigininClicked:(id)sender;
- (IBAction)backgroundTap:(id)sender;

@end

DICViewController.m:

#import "NewViewController.h"

@interface DICViewController ()

@end

@implementation DICViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)sigininClicked:(id)sender {
{
    [self performSegueWithIdentifier:@"login_success" sender:self];
}
}

- (IBAction)backgroundTap:(id)sender {
    [self.view endEditing:YES];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

@end

NewsViewController.h(另一个视图控制器):

#import <UIKit/UIKit.h>

@interface NewViewController : UIViewController
@property (weak, nonatomic) IBOutlet UILabel *steamId; //my label

@end

NewsViewController.m:

此处未添加任何代码。

提前感谢任何有帮助的人。

同样,我希望能够将标签中的文本设置为用户在文本字段中键入的文本。

2 个答案:

答案 0 :(得分:4)

执行segue时,将数据从一个视图控制器传递到另一个视图控制器的首选方法是使用方法-prepareForSegue:sender:

在您的情况下,以下代码行应该有效:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    NewsViewController *newsVC = segue.destinationViewController;
    [newsVC view]; // this loads the view so that its subviews (the label) are not nil
    newsVC.steamID.text = self.txtUsername.text;
}

(将此方法放在DICViewController.m的任意位置。)

答案 1 :(得分:1)

我认为更好的方法是设置全局变量。只做正常的课程

variables.h

#import <Foundation/Foundation.h>

@interface variables : NSObject {
    float VariableYouWant;
}

+ (_tuVariables *)sharedInstance;

@property (nonatomic, assign, readwrite) float VariableYouWant;

和 variables.m

#import "variables.h"

@implementation variables

@synthesize VariableYouWant = _VariableYouWant;


+ (_tuVariables *)sharedInstance {
    static dispatch_once_t onceToken;
    static variables *instance = nil;
    dispatch_once(&onceToken, ^{
        instance = [[variables alloc] init];
    });
    return instance;
}

- (id)init {
    self = [super init];
    if (self) {

    }
    return self;
}

@end

使用方法: 导入变量的头文件和

variables  *globals = [variables sharedInstance];

只需使用

访问变量
globals.VariableYouWant =