0

有人可以看看我哪里出错了吗?

我有一个名为 Object 的对象,它有一个 NSString 属性。

然后我有一个带有按钮的 MainViewController。该按钮以编程方式创建并在运行时添加。

当您单击此按钮时,应该将 Object 的值设置为 String,并将其传递给下一个 ViewController。

我设法设置了 Object 属性的值,但是当我调用该值来传递它时,它被设置为 null。我尝试了许多不同的解决方案,但似乎没有任何效果。谁能看到我的问题出在哪里?我在下面添加了所有相关代码

对象.h

@interface Object : NSObject
@property (nonatomic, strong) NSString *content;

对象.m

#import "Object.h"
@implementation Object
@synthesize content;

然后在 MianViewController 我创建按钮并设置对象属性 MainViewController.h 的值

@interface MainViewController : UIViewController
@property (nonatomic, strong) UIButton *myButton;

主视图控制器.m

#import "MainViewController.h"
#import "SecondaryViewController.h"
#import "Object.h"
.
.
@synthesize myButton;

- (void)viewDidLoad
{
    [super viewDidLoad];

    myButton = [UIButton buttonWithType:UIButtonTypeCustom];
    myButton.tag = 1;
    myButton.frame = CGRectMake(20, 140, 280.f, 40.f);
    UIImage *airButton = [UIImage imageNamed:@"gettingHereByAirButton.png"];
    [myButton setBackgroundImage:airButton forState:UIControlStateNormal];
    [self.view addSubview:myButton];
    [myButton addTarget:self action:@selector(myButtonClicked) forControlEvents:UIControlEventTouchUpInside];
}

- (void) myButtonClicked
{
    [self performSegueWithIdentifier:@"mySegue" sender:self];
}

- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    NSLog(@"Getting Here...");

    Object *object = [[Object alloc] init];
    object.content = @"This is the content of the Object";

    NSLog(@"Content of Object Set To: %@", object.content);

    SecondaryViewController *vc;
    vc.object = object;

    NSLog(@"Object: %@", object);
    NSLog(@"Object.content: %@", object.content);
    NSLog(@"ViewController.object.content: %@", vc.object.content);

    NSLog(@"Just Did Stuff...");
}

以及应将标签设置为 Object String SecondaryViewController.h 的 SecondaryViewController

#import "Object.h"

@interface SecondaryViewController : UIViewController
@property (weak, nonatomic) IBOutlet UILabel *contentLabel;
@property (nonatomic, strong) Object *object;

SecondaryViewController.m

@synthesize object;
@synthesize contentLabel;

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSLog(@"Content of Object: %@", object.content);

    self.contentLabel.text = object.content;
}

最后是应用程序运行时我的 NSLog 的屏幕截图这里

4

1 回答 1

3
SecondaryViewController *vc;

应该

SecondaryViewController *vc = (SecondaryViewController *)segue.destinationViewController;
于 2013-11-06T21:43:31.430 回答