NSNotificationCenter接收事件方法正在执行多次

Nav*_*ved 4 iphone objective-c

我基本上是一个Java开发人员,最近在Objective C(iPhone)上分配了一个任务.

我已开始使用该语言进行编码.但在实施NSNotificationCenter时,我遇到了一个非常奇怪的问题.

解释我的问题非常困难.

我的类A有一个名为NSMutableArray指针类型的数组的全局变量.class的init方法看起来像

- (id) init  
{  
  if(self = [init])  
  {  
    [NSNotificationCenter defaultCenter] addObserver:self @selector(successLogin) name:"successLogin" object:nil];  
    [NSNotificationCenter defaultCenter] addObserver:self @selector(failureLogin) name:"failureLogin" object:nil];  
   ... <some code>  

}
Run Code Online (Sandbox Code Playgroud)

收到事件方法看起来像

- (void) successLogin: (NSNotification * ) notification
{  
   ... <some code of writing data to db using **array**>  
   [self showSuccessAlert]; // it is showing UIAlert
}
Run Code Online (Sandbox Code Playgroud)

sendEvent方法(其他类B)的代码类似于

[[NSNotificationCenter defaultCenter] postNotificationName:@"successLogin" object:nil];
Run Code Online (Sandbox Code Playgroud)

A类有一个按钮" Validate ",它调用B类的方法并验证用户输入的用户ID和密码.如果登录成功,则观察者通知观察者然后将登录信息添加到数据库.该应用程序允许更新db以进行5种不同的登录.(用户ID和密码)

如果我输入第一条记录,它就有效.当我再添加一个登录信息时,通知警报会出现两次.当我再添加一个时,它需要三次,依此类推.它还使用第一个记录添加时的数组值更新db

但是当我输入第一条记录并退出应用程序时(通过从最小化的iPhone和模拟器列表中删除应用程序)并再次运行它并尝试添加第二条记录.它正确添加它.因此,对于5次添加,我必须重复上述循环,这对用户来说当然不方便.

请帮我把这个问题拖出来.

Nav*_*ved 5

在尝试了很多方法之后,我终于得到了解决方案.
以下是我想与您分享的解决方案.

我的A类有一个"Add New"按钮,它调用B类进行ID和密码的连接和认证.基于输出(成功或失败)的B类发布通知,其应由A类处理.

我在dealloc方法中编写了remove observer,这实际上导致了问题,因为该方法根本没有被调用.

因此我在处理程序事件方法中移动了代码.现在我的方法看起来像这样

`

- (void) successLogin: (NSNotification * ) notification
{  
   ... <some code of writing data to db using **array**>  
   [self showSuccessAlert]; // it is showing UIAlert  

[[NSNotificationCenter defaultCenter] removeObserver: self];  
}  
Run Code Online (Sandbox Code Playgroud)

`

此外,我将addObserver的代码从init转移到AddNewButtonAction.事情开始正常.