Search code examples
objective-ccocoansnotificationcenter

Why @selector can call a method which is declared in an implementation file?


I have declared (between @interface and @end) and implemented a method in the .m file of Class A. For instance:

- (void)zoneChange:(NSNotification *)note
{
    NSLog(@"The system time zone has changed!");
}

And in Class B, I want to send zoneChange message to a observer when the system zone is changed.

[[NSNotificationCenter defaultCenter] addObserver:anObserver
                                         selector:@selector(zoneChange:)
                                             name:NSSystemTimeZoneDidChangeNotification
                                           object:nil];

The code above works. When user changes the time zone on Mac, zoneChange method get called. However, the compiler gives me a warning about the @selector: Undeclared selector "zoneChange:". What confused me is that sincezoneChange is a private method, why can it been seen by the @selector in Class B beyond the Class A? Anyone can explain it for me?


Solution

  • Private methods are just that: private. They still exist, they're just kept secret from the outside world. There's nothing built in to Objective-C to check where a method is being called from and complain at runtime; that compile-time warning about an undeclared selector is exactly the failure of Class B to see the method that you expect!