I am basically a Java developer and recently assigned a task on objective C (iPhone).
I have started coding in the language. but while implementing the NSNotificationCenter I am having very strange problem.
It is very difficult to explain my problem.
My class A is having one global variable named array of type NSMutableArray Pointer. class's init method looks something like
- (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>
}
recieve event method looks like
- (void) successLogin: (NSNotification * ) notification
{
... <some code of writing data to db using **array**>
[self showSuccessAlert]; // it is showing UIAlert
}
The sendEvent method (of other class B) is having code something like
[[NSNotificationCenter defaultCenter] postNotificationName:@"successLogin" object:nil];
The class A is having one button "Validate" which calls class B's method and validate the user id and password entered by the user. it notify the observer if login is successful and observer is then Adding the login info to the db. The application allows to update db for 5 different login. (userid & password)
it works if I enter 1st record. when I add one more login info, the notification alert comes for twice. When I add one more it comes for thrice and so on. Also it updates db with the value of array which was at the time of 1st record addition
but when I enter 1st record and quit the application (by removing the application from minimize list of iPhone as well as Simulator) and again run it and tries to add second record. It adds it correctly. so for 5 additions I have to repeat the above cycle which is of course not conveniently for user.
Please help me to drag me out from this problem.
After trying lots of way, I finally got the solution.
Following is the solution which I want to share with you.
My Class A was having a button "Add New", which calls Class B for connection and authentication of id and password. The class B, based on the output (success or failure) posts the notification, which in terms should be handle by Class A.
I wrote the remove observer in dealloc method, which was actually causing the problem because the method was not at all being called.
and hence I shifted the code in my handler event method. now my method does look like this
`
- (void) successLogin: (NSNotification * ) notification
{
... <some code of writing data to db using **array**>
[self showSuccessAlert]; // it is showing UIAlert
[[NSNotificationCenter defaultCenter] removeObserver: self];
}
`
Also, I shifted the code of addObserver from init to AddNewButtonAction. So the things started working correctly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With