gpt4 book ai didi

iphone - 在 Storyboard 中使用 NSNotification

转载 作者:行者123 更新时间:2023-11-28 18:39:33 25 4
gpt4 key购买 nike

我正在尝试在我的Storyboard 中使用 NSNotification。

当我不使用 Storyboard 时,此代码有效。

这是在 ViewController1 中:

- (IBAction) buttonClickedListener2:(id)sender {
[[NSNotificationCenter defaultCenter]
postNotificationName:@"TestNotification"
object:self];
}

这是在 ViewController2 中:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(receiveTestNotification:)
name:@"TestNotification"
object:nil];

NSLog(@"initWithNib");
}
return self;
}

- (void) receiveTestNotification:(NSNotification *) notification
{
// [notification name] should always be @"TestNotification"
// unless you use this method for observation of other notifications
// as well.

if ([[notification name] isEqualToString:@"TestNotification"])
NSLog (@"Successfully received the test notification!");
}

代码有问题吗?正如我所说,我想让它在我的 Storyboard 中发挥作用。

如果你给我一些关于如何在 STORYBOARD 中使用 NSNotification 的教程,我将不胜感激。

最佳答案

您应该不在 initWithNibName 中而是在 awakeFromNib 中添加观察者。 initWithNibName 不会为 Storyboard调用。

例如:

- (void)awakeFromNib {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(receiveTestNotification:)
name:@"TestNotification"
object:nil];
}

关于iphone - 在 Storyboard 中使用 NSNotification,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13029155/

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