在目标控制器中设置 class 的 属性

Set property of a class in a destination controller

我正在尝试设置在目标转场中实例化的 class 的 属性。

具体来说,我有一个带有按钮的根视图控制器。该按钮只是通过故事板连接到另一个视图控制器。在 prepareForSegue 中,我实例化目标视图控制器,然后设置 属性。

当 属性 是目标的简单 object(int、NSInt、NSString 等)时,赋值就起作用了——也就是说,我可以在赋值前后使用 NSLog 并查看值从零变为我指定的数字。

但是,当 属性 是我创建的简单 class 的实例时,没有编译或运行时错误,但值仍然为零。

我尝试过的事情:

我的理解是@synthesize 是自动完成的,但我还是试过了。

我也试过将属性放在 class header 界面中,但我认为也没有必要。

我还使用以下代码构建了一个新项目,以确保它不只是一些奇怪的东西,因为它是一个更大的应用程序的一部分。我排除了向后转场的代表,因为它工作正常。

我找到了很多转发数据的例子,但我找不到任何我需要的带有 class 的东西。

鉴于没有错误,这感觉像是范围或初始化问题,但经过 3 天的摸索,我没有想法。

// menuViewController.h

#import <UIKit/UIKit.h>
#import "Settings.h"
#import "setupViewController.h"

@interface menuViewController : UIViewController
@end

// menuViewController.m

#import "menuViewController.h"

@interface menuViewController ()
@property (weak, nonatomic) IBOutlet UIButton *myButton;

@end

@implementation menuViewController {
Settings *menuSettings;
}

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"toSecond"]) {
        setupViewController *instanceOfSetupViewController = segue.destinationViewController;

        // This assign doesn't change the property in the destination
        instanceOfSetupViewController.myLocalSettings.bpm = 67;

        // This local assign works
        menuSettings.bpm = 77;
        // But this assign doesn't change the property in the destination
        instanceOfSetupViewController.myLocalSettings = menuSettings;
    }
}

- (IBAction)prepareForUnwind:(UIStoryboardSegue *)segue {}

// setupViewController.h

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

@interface setupViewController : UIViewController

@property () Settings* myLocalSettings;
@end

// setupViewController.m

#import "setupViewController.h"

@interface setupViewController ()
@property (weak, nonatomic) IBOutlet UIButton *myButton;

@end

@implementation setupViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    Settings *myLocalSettings = [[Settings alloc] init];
    myLocalSettings.bpm = 13;
}

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

// Settings.h

#import <Foundation/Foundation.h>

@interface Settings : NSObject

@property () NSInteger bpm;
@end

// Settings.m

#import "Settings.h"
@implementation Settings
@end

谢谢!

不行,因为你还没有创建Settings对象,所以myLocalSettings为nil。在调用 prepareForSegue 时,目标视图控制器的视图尚未加载,因此您在 viewDidLoad 中实例化的 Settings 对象还没有创建(您应该删除那个对象,否则它将覆盖您在此处创建的对象)。您应该首先在 prepareForSegue 中创建该实例,

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"toSecond"]) {
        setupViewController *instanceOfSetupViewController = segue.destinationViewController;
        instanceOfSetupViewController.myLocalSettings = [Settings new];
        instanceOfSetupViewController.myLocalSettings.bpm = 67;
    }
}