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

标签 objective-c cocoa

我正在设置窗口的父属性,当我检查 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/

相关文章:

ios - 如何在不使用 [view setNeedsDisplay] 的情况下使用 NSNotification 刷新 View ;

ios - 当网络连接缓慢时应用程序卡住,因为 POST API 调用发生在应用程序启动时。下面是我的连接管理器代码,Objective-C,iOS

ios - 将 WCSession 的委托(delegate)设置为 nil

cocoa - 当 NSTableView 的数据源发生变化时,如何更新它?

swift - NSAttributedString dataFromRange 生成没有任何尾部缩进的 docx 文件

iphone - respondsToSelector 总是失败

iphone - 从observeValueForKeyPath 调用方法。

objective-c - 寻找过度释放的根源

cocoa - Xcode 中带有 Core Data 的高级数据模型

macos - (Cocoa) NSScrollView 与 IKImageBrowserView 滚动到底部