Reputation: 996
So i have a class that adds itself as observer in NSNotificationService on init and on dealloc removes itself from NSNotificationCenter.
Everything works great, i post notification and receive it once and with correct object.
Then i did a loop and added three views. Each view got called init once, all views added itself as observer.
Now when i post notification, each view receives its notification three times! (9 in total)
So i moved my add observer to another method and called it only on two views (from those three).
Now each view got called twice (three views called two times, 6 total) although third instance was not even added as observer (watched metgod, did not get called as expected).
Now i removed loop and created three views. And added only one as observer. All three got called...
Is this known issue or did i find something new?
XCode 4.6 iOS 6.1
UPDATE---------------
Problem is, that my View is actually just one instance.
This code produces three views that are all the same one view.
CustomViewController * hw1 = [[CustomViewController alloc] init];
[hw1 setupWithFrame:CGRectMake(
contentScrollView.frame.size.width * 0 + contentScrollView.frame.size.width/2 - 250 ,
contentScrollView.frame.size.height / 2 - 250,500,500)];
[contentScrollView addSubview:hw1.view];
CustomViewController * hw2 = [[CustomViewController alloc] init];
[hw2 setupWithFrame:CGRectMake(
contentScrollView.frame.size.width * 1 + contentScrollView.frame.size.width/2 - 250 ,
contentScrollView.frame.size.height / 2 - 250,500,500)];
[contentScrollView addSubview:hw2.view];
CustomViewController * hw3 = [[CustomViewController alloc] init];
[hw3 setupWithFrame:CGRectMake(
contentScrollView.frame.size.width * 2 + contentScrollView.frame.size.width/2 - 250 ,
contentScrollView.frame.size.height / 2 - 250,500,500)];
[contentScrollView addSubview:hw3.view];
Changing content in hw1, changes content in hw2 and hw3.
SetupWithFrame is just a method that allocates and adds subviews of defined frame.
Upvotes: 1
Views: 178
Reputation: 996
The loop was here:
When I created a view A and set it to observe calls from Data, A told Data to update.
Now view B also was set as observer and told Data to update.
In the end, Data was told to update three times, and since it updated it told all observers about new data (three times) and the views all acted identically (not the same instance after all) since they received data meant for other views.
Upvotes: 0
Reputation: 46563
Here is your root of problem:
You created three instances of hw1
, hw2
, hw3
in a loop and added them to [contentScrollView addSubview:
.
So your contentScrollView now has total of nine subviews, each having their own observers.
That is why your notifications are observed nine times.
Upvotes: 0
Reputation: 4246
remove your observer every time before adding the observer. Its obviously being added multiple times
Upvotes: 0