天天看点

ios 通知NSNotificationCenter 的名字可否同名

最近公司招人,面试了几个人,总是问这么个问题,

当我创建通知时可否创建两个同名的通知,竟没有一个人回答说可以。

经过实测在同一个项目中可以存在多个同名的通知,最后造成的结果是创建了几个这个通知就发送给了各自的通知。

比如我在两个类里面都创建了名为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

所以我觉的程序员要追求“为什么”是很有必要的