我正在为我的iPhone应用程序开发一个类,我希望它注册并了解应用程序状态的更改(UIApplicationDidEnterBackgroundNotification
等)。有没有一种方法可以为通知注册一个类,而不必在内存中保留实例化的对象?我只想让适当的通知调用类初始化,做一些事情,然后再次离开内存。
现在,我在init方法中有以下内容:
[[NSNotificationCenter defaultCenter] addObserver: self
selector: @selector(handleEnteredBackground)
name: UIApplicationDidEnterBackgroundNotification
object: nil];
这个方法在类的.m文件的其他地方:
- (void) handleEnteredBackground {
NSLog(@"Entered Background"); }
我在applicationDidLoad
下实例化了一次类,但由于我没有对它做任何操作,我认为ARC会从内存中杀死对象,当我关闭它时,应用程序会崩溃(请注意,没有任何有用的错误代码)。如果我将handleEnteredBackground
切换到带"+"号的类方法,那么当我关闭应用程序时,我会收到无效的选择器错误。
最终目标是在应用程序的生命周期中实例化一个类,并使其能够响应应用程序状态的更改,而无需在类之外添加任何其他代码。假设iOS 5+Xcode 4.2+
以下内容应该有效:
[[NSNotificationCenter defaultCenter] addObserver: [self class]
selector: @selector(handleEnteredBackground:)
name: UIApplicationDidEnterBackgroundNotification
object: nil];
选择器本身:
+ (void) handleEnteredBackground: (NSNotification *) notification
{
}
您不必注销观察器,因为类对象不能被释放或以其他方式销毁。如果由于其他原因需要注销观察器,您可以:
[[NSNotificationCenter defaultCenter] removeObserver: [self class]];
您应该研究singleton。
您可以轻松地创建一个贯穿整个应用程序生命周期的对象。
+ (id)sharedObserver
{
static dispatch_once_t once;
static YourObserverClass *sharedObserver = nil;
dispatch_once(&once, ^{
sharedObserver = [[self alloc] init];
});
return sharedObserver;
}
- (void)startObserving
{
// Add as observer here
}
现在您可以调用[[YourObserverClass sharedObserver] startObserving]
,不必担心保留它等问题。