CNContactStoreDidChangeNotification被多次触发 [英] CNContactStoreDidChangeNotification is fired multiple times
问题描述
当应用程序处于后台状态时更改联系人数据库时,我能够观察到 CNContactStoreDidChangeNotification
。我很确定只有一个观察者被添加到 NSNotificationCenter
。
问题是 NSNotificationCenter
发布多次(2,3,5甚至更多次)即使我只添加一个新联系人。
问题出在哪里?
I am able to observe the CNContactStoreDidChangeNotification
when the contact database is changed while the app is in background state. I am pretty sure that only one observer was added to NSNotificationCenter
.
The problem is NSNotificationCenter
posts MULTIPLE times (2, 3, 5, and even more times) even if I only add one new contact.
Where is the problem?
推荐答案
确保您没有多次添加观察者。如果(例如)从 -viewDidLoad
或<$ c $调用 -addObserver
,则可能会发生这种情况。 c> -viewDidAppear 在视图控制器中(因为这些可能在应用程序的整个生命周期中被多次调用),或者来自应用程序委托中的任何应用程序状态回调( -applicationDidBecomeActive
, -applicationWillResignActive
, -applicationDidEnterBackground
, - applicationWillEnterForeground
等。)
Make certain you aren't adding the observer multiple times. This can happen without you realizing it if (for example) you call -addObserver
from -viewDidLoad
or -viewDidAppear
in your view controller (as these might get called more than once throughout the life of your application), or from any of the application state callbacks in your app delegate (-applicationDidBecomeActive
, -applicationWillResignActive
, -applicationDidEnterBackground
, -applicationWillEnterForeground
, etc).
将条件包含在 -addObserver
中确保它只能被调用一次(设置一个标志),并在它周围放置NSLog语句,这样你就可以在调试控制台中看到你是否多次到达那里。在您的代码中搜索您可能忘记的 -addObserver
的其他电话。
Wrap the call to -addObserver
in a conditional that ensures it can only be called once (set a flag), and put NSLog statements around it so you can see in the debug console if you are getting there more than once. Search your code for other calls to -addObserver
that you might have forgotten about.
致电 -removeObserver
在添加它之前,为了确保(确保传递与添加它时相同的名称和对象)。在不存在的观察者上调用 -removeObserver
是可以的。 请注意,这更像是一个创可贴而非修复 - 您的代码应该足够聪明,知道您是否已经添加了它 - 但这可能有助于您诊断问题。
Call -removeObserver
before adding it, just to be sure (making sure to pass the same name and object as when you added it). Calling -removeObserver
on an observer that doesn't exist is okay. Note that this is more of a band-aid than a fix - your code should be smart enough to know whether or not you've already added it - but this might help you diagnose the problem).
我刚写了一个快速的最小测试程序,它在 CNContactStoreDidChangeNotification
上添加一个观察者(一次!),我只得到了添加或更改联系人时的通知。为自己写一个类似的测试程序,看看你是否得到了相同的结果。如果您的测试程序正常运行,那么您的应用程序可能正在执行您不期望的操作(并且多次调用 -addObserver
)。
I just wrote a quick minimal test program that adds an observer (once!) on CNContactStoreDidChangeNotification
and I only get the notification once when I add or change a contact. Write a similar test program for yourself and see if you get the same result. If your test program works correctly, then it is likely that your app is doing something you don't expect (and calling -addObserver
multiple times).
这篇关于CNContactStoreDidChangeNotification被多次触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!