【发布时间】:2015-05-17 00:12:12
【问题描述】:
我正在尝试设置在目标 segue 中实例化的类的属性。
具体来说,我有一个带有按钮的根视图控制器。该按钮只是通过故事板连接到另一个视图控制器。在 prepareForSegue 中,我实例化了目标视图控制器,然后设置了一个属性。
当属性是目标的简单对象(int、NSInt、NSString 等)时,分配有效 - 即我可以在分配前后 NSLog 并看到值从零变为我分配的数字.
但是,当属性是我创建的简单类的实例时,没有编译或运行时错误,但值保持为零。
我尝试过的事情:
我的理解是@synthesize 是自动完成的,但我还是尝试了。
我也尝试将属性放在类头接口中,但我认为也不需要。
我还使用下面的代码构建了一个新项目,以确保它不仅仅是一个奇怪的东西,因为它是一个更大的应用程序的一部分。我排除了后向 segue 的委托,因为它工作正常。
我找到了很多向前传递数据的例子,但我找不到任何我需要的类。
鉴于没有错误,这感觉像是一个范围或初始化问题,但经过 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];
}
// 设置.h
#import <Foundation/Foundation.h>
@interface Settings : NSObject
@property () NSInteger bpm;
@end
// 设置.m
#import "Settings.h"
@implementation Settings
@end
谢谢!
【问题讨论】:
标签: ios objective-c xcode class uiviewcontroller