最近公司招人,面試了幾個人,總是問這麼個問題,
當我建立通知時可否建立兩個同名的通知,竟沒有一個人回答說可以。
經過實測在同一個項目中可以存在多個同名的通知,最後造成的結果是建立了幾個這個通知就發送給了各自的通知。
比如我在兩個類裡面都建立了名為test的通知,
gkfdd類
#import "gkfdd.h"
@implementation gkfdd
- (id)init {
self = [super init];
if (!self) {
return nil;
}
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(fjsd) name:@"test" object:nil];
return self;
}
- (void)fjsd {
NSLog(@"haha1");
}
@end
fds類
#import "fds.h"
@implementation fds
- (id)init {
self = [super init];
if (!self) {
return nil;
}
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(fjsd) name:@"test" object:nil];
return self;
}
- (void)fjsd {
NSLog(@"haha2");
}
@end
ViewController類
#import "ViewController.h"
#import "gkfdd.h"
#import "fds.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
gkfdd *s = [[gkfdd alloc] init];
fds *d = [[fds alloc] init];
[[NSNotificationCenter defaultCenter] postNotificationName:@"test" object:self];
//[[NSNotificationCenter defaultCenter] postNotificationName:@"haha" object:self userInfo:nil];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
最後列印出
2015-11-05 15:48:29.512 notification[20402:3347336] haha1
2015-11-05 15:48:29.512 notification[20402:3347336] haha2
是以我覺的程式員要追求“為什麼”是很有必要的