NSNotificationCenter postNotificationName crash

postNotificationName:XXXXXX carsh

[[NSNotificationCenter defaultCenter] postNotificationName:XXXXXX object:self];

经过推理得出结论:
因为通知是全局异步的,self有可能被释放掉了,或许通知没用对数据加锁or something
网上搜索也得出了相似的答案

  • I've seen no documentation that promises that. You can try to explore it by making dealloc very slow (using sleep() for instance) and adding printf() logging. (Never do threading analysis with NSLog.) But I doubt you could rely on the results. Even if ARC promised it, you can't know whether NSNotificationCenter uses ARC internally. The only real promises are what you get from the docs. – Rob Napier Dec 6 '12 at 18:05

这样使用为什么会有崩溃问题呢?
因为会随机遇见僵尸内存问题

Are there any workaround for randomly crash?

Enable zombies - this will cause the exception to breakpoint on the offending line. From there it will be a lot easier to figure out than the general EXC_BAD_ACCESS crash.

那如何解决呢?
1 .翻看sdwebimage源码看到了如下代码(本人未验证)(以测试,没有用)

__block typeof(self) strongSelf = self;

[[NSNotificationCenter defaultCenter] postNotificationName:XXXXXX object:strongSelf ];

2.转地址(本人未验证)
地址获取与此类似

__block typeof(self) strongSelf = self;
NSInteger  nSelf = (long)(__bridge void *)self;
NSNumber  *number = @(nSelf);
[[NSNotificationCenter defaultCenter] postNotificationName:XXXXXX object:number];

//接受通知对象转换成self
NSObject *obj = (__bridge NSObject*) object.integerValue;

你可能感兴趣的:(NSNotificationCenter postNotificationName crash)