在iOS中传递值

时间:2013-07-05 02:44:16

标签: ios objective-c

我创建了两个页面,名为ViewController和SecViewController。在ViewController中,它是第一个页面,带有一个按钮和一个标签。然后我在按钮上设置segue到SecViewController,这是第二页。

我正在尝试将segue标识符传递给第2页,但这并不成功。我测试了第1页传递的值,控制台显示

  

2013-07-05 10:33:54.554 Testing2 [1314:c07] 1,(null)

这是我的代码: 任何人都可以识别我输错的代码?

ViewController.h

#import <UIKit/UIKit.h>

@class SecViewController;

@interface ViewController : UIViewController

@property (strong, nonatomic) IBOutlet UILabel *label;
@property (strong, nonatomic) IBOutlet UIButton *button;

@property (strong, nonatomic) SecViewController *view2;

@end

ViewController.m

#import "ViewController.h"
#import "SecViewController.h"

@implementation ViewController

@synthesize label, button, view2;

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if ([[segue identifier] isEqualToString:@"1"]){
        view2.received  = [segue identifier];
        NSLog(@"%@, %@", [segue identifier], view2.received);
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [label setText:@"Game Start!"];
}

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

@end

SecViewController.h

#import <UIKit/UIKit.h>

@interface SecViewController : UIViewController

@property (strong, nonatomic) id received;
@property (strong, nonatomic) IBOutlet UILabel *label;

@end

SecViewController.m

#import "SecViewController.h"

@implementation SecViewController

@synthesize label;

- (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.
}

@end

1 个答案:

答案 0 :(得分:0)

您不必为第二个视图控制器创建属性。您可以在prepareForSegue中获取它并从第二个视图控制器访问接收到的变量。

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if ([[segue identifier] isEqualToString:@"1"]){
        SecViewController *vc  = [segue destinationViewController];
        vc.received = [segue identifier];
        NSLog(@"%@, %@", [segue identifier], vc.received);
    }
}

如果你在secondviewcontroller中输入了所收到的值的内容,那么你会得到什么?

#import "SecViewController.h"

@implementation SecViewController

@synthesize label;

- (void)viewDidLoad
{
    [super viewDidLoad];
NSLog(@"Received %@",self.received);
    // Do any additional setup after loading the view, typically from a nib.
}

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

@end