NSNotification选择器方法未被调用

时间:2016-06-17 12:16:26

标签: ios objective-c nsnotificationcenter

我正在使用NSNotification在ViewControllers之间传递值,但是没有传递值,当我使用断点检查出错时我知道没有调用接收通知选择器方法。 以下是我写的代码

AViewController.m

[[NSNotificationCenter defaultCenter] postNotificationName:@"speciality" object:nil userInfo:[specialityIdArray objectAtIndex:indexPath.row]];

BViewCOntroller.m

-(void)viewWillAppear:(BOOL)animated
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveSpecialityId:) name:@"speciality" object:nil];

}

-(void)receiveSpecialityId:(NSNotification *)notificaton
{

    NSString *selectedServiceString=[[notificaton userInfo] valueForKey:@"service"];

    _specialtiyId = selectedServiceString;

    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"service" object:nil ];
}

我正在尝试将值从AViewController传递给BViewController

我已经阅读了之前在同一问题上所做的所有讨论,但没有一个解决了我的问题

1 个答案:

答案 0 :(得分:0)

不要'添加

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveSpecialityId:) name:@"speciality" object:nil];
viewDidAppear中的

。我不太了解客观情况,但这里的交易很快:

func receiveSpecialityID(notification: NSNotification){

  NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(<Theclassinwhichthismethodiswritten without the ()).receiveSpecialityID(_:)), name: "Selected", object: nil)   
 /// DO your thing here..
}

然后做一个:

deinit{
NSNotificationCenter.DefaultCenter().removeObserver

}

这应该有效。试试让我知道!