我基本上是一名 Java 开发人员,最近分配了一项关于目标 C (iPhone) 的任务。
我已经开始用这种语言编码。但是在实现 NSNotificationCenter 时,我遇到了非常奇怪的 问题 。
很难解释我的问题。
我的 A 类有一个名为 数组 的全局变量,类型为 NSMutableArray 指针。类的 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>
}
接收事件方法看起来像
- (void) successLogin: (NSNotification * ) notification
{
... <some code of writing data to db using **array**>
[self showSuccessAlert]; // it is showing UIAlert
}
sendEvent 方法(其他 B 类)的代码类似于
[[NSNotificationCenter defaultCenter] postNotificationName:@"successLogin" object:nil];
A 类有一个按钮“ Validate ”,它调用 B 类的方法并验证用户输入的用户 ID 和密码。如果登录成功,它会通知观察者,然后观察者将登录信息添加到数据库中。该应用程序允许为 5 个不同的登录更新数据库。 (用户名和密码)
如果我输入第一条记录,它会起作用。当我再添加一个登录信息时,通知警报会出现两次。当我再添加一个时,它会出现三次,依此类推。它还使用添加第 1 条记录时的数组值更新 db
但是当我输入第一条记录并退出应用程序时(通过 从 iPhone 的最小化列表中删除应用程序以及模拟器 )并再次运行它并尝试添加第二条记录。它正确地添加了它。所以对于 5 个添加,我必须重复上述循环,这对用户来说当然不方便。
请帮我把我从这个问题中拖出来。
最佳答案
尝试了很多方法后,我终于得到了解决方案。
以下是我想与您分享的解决方案。
我的 A 类有一个按钮“添加新”,它调用 B 类来连接和验证 id 和密码。 B 类基于输出(成功或失败)发布通知,就其而言应由 A 类处理。
我在 dealloc 方法中编写了删除观察者,这实际上导致了问题,因为根本没有调用该方法。
因此我 移动了我的处理程序事件方法 中的代码。现在我的方法看起来像这样
`
- (void) successLogin: (NSNotification * ) notification
{
... <some code of writing data to db using **array**>
[self showSuccessAlert]; // it is showing UIAlert
[[NSNotificationCenter defaultCenter] removeObserver: self];
}
`
另外,我将 addObserver 的代码从 init 转移到 AddNewButtonAction 。
所以事情开始正常工作。