Ios 在视图之间发送通知

Ios 在视图之间发送通知,ios,objective-c,nsnotificationcenter,nsnotifications,Ios,Objective C,Nsnotificationcenter,Nsnotifications,这是我第一次尝试使用NSNotification,尝试了几本教程,但不知怎么的,它不起作用 基本上,我正在向类B发送一个字典,它是弹出子视图(UIViewController),并测试是否已收到 谁能告诉我我做错了什么 甲级 - (IBAction)selectRoutine:(id)sender { UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Storyboard" bundle:nil]; NS

这是我第一次尝试使用
NSNotification
,尝试了几本教程,但不知怎么的,它不起作用

基本上,我正在向类B发送一个字典,它是弹出子视图(
UIViewController
),并测试是否已收到

谁能告诉我我做错了什么

甲级

- (IBAction)selectRoutine:(id)sender {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Storyboard" bundle:nil];

    NSDictionary *dictionary = [NSDictionary dictionaryWithObject:@"Right"
                                                           forKey:@"Orientation"];
    [[NSNotificationCenter defaultCenter]
     postNotificationName:@"PassData"
     object:nil
     userInfo:dictionary];

    createExercisePopupViewController* popupController = [storyboard instantiateViewControllerWithIdentifier:@"createExercisePopupView"];

    //Tell the operating system the CreateRoutine view controller
    //is becoming a child:
    [self addChildViewController:popupController];

    //add the target frame to self's view:
    [self.view addSubview:popupController.view];

    //Tell the operating system the view controller has moved:
    [popupController didMoveToParentViewController:self];

}
B类

- (void)viewDidLoad
{
    [super viewDidLoad];

    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(receiveData:)
     name:@"PassData"
     object:nil];
}

- (void)receiveData:(NSNotification *)notification {
    NSLog(@"Data received: %@", [[notification userInfo] valueForKey:@"Orientation"]);
}

如果它还没有注册接收该通知,它将永远不会收到它。通知不会持久存在。如果没有注册的侦听器,则发布的通知将丢失。

针对您的问题,在发送通知之前,接收者尚未开始观察,因此通知将丢失

更一般地说:你做错的是在这个用例中使用通知。如果你只是在玩游戏和做实验,这是很好的,但是你在这里建模的那种关系最好通过保留对视图的引用并直接调用它的方法来实现。如果实验是实际使用情况的真实情况,通常是最好的

您应该了解3种基本的沟通机制以及何时使用它们:

通知 使用它们通知其他未知对象发生了什么。当你不知道谁想对事件做出回应时,使用它们。当多个不同的对象想要响应事件时使用它们

通常,观察者一生中的大部分时间都是注册的。重要的是要确保观察者在被销毁之前将自己从
NSNotificationCenter
中移除

授权 当一个对象希望从未知源获取数据或将某些决策的责任传递给未知的“顾问”时,使用委托

方法
当您知道目标对象是谁、他们需要什么以及何时需要时,使用直接调用。

在class A发送通知之前是否加载了class B?否,尚未加载。这就是我需要在加载通知后将其移动到的位置。请正确回答,这样我就可以将其标记为已回答。thanksMove
[[NSNotificationCenter defaultCenter]postNotificationName:@“PassData”对象:nil用户信息:dictionary]创建类B之后,它尚未注册以接收该通知。通知不会持久存在。如果没有注册的侦听器,它们将永远消失。您的列表中缺少KVO。