让NSNotification工作?

时间:2013-05-08 06:20:53

标签: iphone ios objective-c uiwebview nsnotifications

我目前正在努力让NSNotification工作,但我遇到了一些麻烦。

我有两个(2)ViewControllers:A。MainViewController& B. LoginViewController。

在我的MainViewController中,我有一个注销按钮,它会向我的LoginViewController发送一个url来加载它(不显示我的loginView)。但是,它没有用。

在我的MainViewController中,这就是我所拥有的:

- (IBAction)logout:(id)sender {

NSURL *logoutURL = [NSURL URLWithString:@"https://myurl.com/logout"];

[[NSNotificationCenter defaultCenter] postNotificationName:@"logoutInitiated" object:logoutURL];


}

这是我在LoginViewController中的内容:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    WebView.delegate = self;
    WebView.scalesPageToFit = YES;
    WebView.multipleTouchEnabled = YES;
    loadCount = 0;

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(submitLogout) name:@"logoutInitiated" object:nil];

}

- (IBAction)submitLogout:(NSNotification*)notification {


   [WebView stopLoading];

    NSURL * signOutUrl = (NSURL*)[notification object];
    [self loadURL:nil withURL:signOutUrl];
}

我的问题是,当我按下logoutButton时没有任何反应。 (使用NSLogs,我发现它永远不会触发下一步)谢谢!!!!

3 个答案:

答案 0 :(得分:1)

这是因为您传入选择器的方法名称错误。您需要在submitLogout:后缀添加冒号 使用

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(submitLogout:) name:@"logoutInitiated" object:nil]; 

取代

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(submitLogout) name:@"logoutInitiated" object:nil];

希望它对你有所帮助。

答案 1 :(得分:0)

当您将self添加为观察者时,您使用选择器“submitLogout”而不使用分号!但是你的方法有一个参数,所以正确的选择器是@selector(submitLogout:)

答案 2 :(得分:0)

请注意 SEMICOLON

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(**submitLogout:**) name:@"logoutInitiated" object:nil];    

- (IBAction)logout:(id)sender 
{
        NSURL *logoutURL = [NSURL URLWithString:@"https://myurl.com/logout"];    
        [[NSNotificationCenter defaultCenter] postNotificationName:@"logoutInitiated" object:nil       userInfo:[NSDictionary dictionaryWithObjectsAndKeys:logoutURL,@"RECEIVED_URL", nil]];
}

- (IBAction)submitLogout:(NSNotification*)notification 
{       
    [WebView stopLoading];
     NSURL * signOutUrl = (NSURL*)[notification objectForKey:@"RECEIVED_URL"];
    [self loadURL:nil withURL:signOutUrl];
}