gpt4 book ai didi

objective-c - IBAction 中属性(property)失去值(value)

转载 作者:行者123 更新时间:2023-12-03 16:32:21 25 4
gpt4 key购买 nike

我正在设置窗口的父属性,当我检查 windowDidLoad 中的属性时,一切都很好。但是当我在 IBAction 中检查它时,它是零。我在这里缺少什么?

AppController.m

loginController = [[LoginController alloc] initWithWindowNibName:@"Login" owner:self];
loginController.parent = self;
[[loginController window] makeKeyAndOrderFront:self];

登录 Controller .h

@property (nonatomic, weak) AppController *parent;

登录 Controller .m @synthesize父级;

- (void)windowDidLoad
{
[super windowDidLoad];

NSLog(@"Parent: %@", self.parent); //<--- Parent: <AppController: 0xblahblah>
}

- (IBAction)login:(id)sender
{
NSLog(@"Parent: %@", self.parent); //<--- nil
}

enter image description here enter image description here enter image description here enter image description here enter image description here

最佳答案

我认为你的问题只是你设置了错误的文件所有者,是保存xib文件的登录 Controller ,因此它绑定(bind)了所有IBOutlet和IBActions。

调用 initWithWindowNibName: 而不是 initWithWindowNibName:owner: ,这样文件所有者将是新创建的登录 Controller ,而不是应用 Controller :

loginController = [[LoginController alloc] initWithWindowNibName:@"Login"];

编辑

就像我怀疑的那样,您有两个独立的登录 Controller 实例,而您认为只有一个。查看xib文件:

enter image description here

xib 文件中的“登录 Controller ”对象创建登录 Controller 的另一个实例。它与您在应用程序 Controller 中分配的实例不同。

解决方案是让父级成为 IBOutlet:

@property (nonatomic, weak) IBOutlet AppController *parent;

并且为了不在应用程序 Controller 中分配它,它将自动从 xib 文件加载。 您所要做的就是将其绑定(bind)到 xib 文件中的登录 Controller 实例(如果文件所有者是应用程序 Controller ,您应该按住 Ctrl 键将父属性拖动到对象图标,告诉我是否你在做这件事时遇到了一些问题)。这就是它打印 null 的原因:该操作由另一个对象处理,该对象尚未初始化父属性。

关于objective-c - IBAction 中属性(property)失去值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15347576/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com