5

Should it be possible to have a static NSNotification observer (like the code below)? I'm having some problems, and I think it may be due to my singleton class structure.

I don't always have a class instance around to listen to the notifications, but the static properties of this class stick around for my application's lifecycle.

- (id)init {
    [super init]

    [[NSNotificationCenter defaultCenter] addObserver:[self class]
                                             selector:@selector(action:aNotification:)
                                                 name:@"NSSomeNotification"
                                               object:nil];
    return self;
}

+ (void)action:(NSNotification *)aNotification {
    NSLog( @"Performing action" );
}
Dov
  • 15,530
  • 13
  • 76
  • 177

1 Answers1

9

The first problem may be your selector — that should be @selector(action:).

Also, are you sure you want to register the notification in init (which is missing any call to [super init], which may be another problem)? That means your notification will be (re)registered every time you create an instance of the class. You might consider implementing a true singleton object instead of class methods.

bosmacs
  • 7,341
  • 4
  • 31
  • 31
  • It was the selector, thanks. I edited my post to reflect that I was calling `[super init]` (I didn't post my entire function). Also, I have a check that makes sure it doesn't get called multiple times, so that's not a problem either. Do you have a link that would show how to make a "true singleton" in Objective-C? – Dov Dec 08 '10 at 11:35
  • [The wikipedia entry](http://en.wikipedia.org/wiki/Singleton_pattern#Objective-C) is a good example of the two main techniques. I often use the non-strict implementation. See also this question & answers: http://stackoverflow.com/questions/145154/what-does-your-objective-c-singleton-look-like – bosmacs Dec 08 '10 at 13:26