我在我的应用程序中实现了NSNotificationCenter。当图像解码完成时,我会发送通知。当图像解码第一次执行8 times.So时,假定发送8 times.But的通知将被调用64次(8*8)。
下面是我的代码如何实现-> //初始化
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(getHRImage:)
name:@"DecodeComplete" object:nil];} //调用方法
-(void)getHRImage:(NSNotification *) notification
{
if ([[notification name] isEqualToString:@"DecodeComplete"])
NSLog (@"Successfully received the DecodeComplete notification! ");
}`//取消分配
- (void) dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"DecodeComplete" object:self];
//[super dealloc];
}//事后通知
[[NSNotificationCenter defaultCenter] postNotificationName:@"DecodeComplete" object:self];有人可以告诉我我做错了什么。
提前谢谢。
//调用方法如下(调用8次)
-(void)decode
{
NSLog(@"---------- Decoding is Complete ---------");
[[NSNotificationCenter defaultCenter] postNotificationName:@"MdjDecodeComplete" object:self];
}发布于 2015-04-22 06:39:10
initWithFrame:(CGRect)frame解决方案:--我重新检查了代码,调用了8次,添加了8次NSNotification观察者。
所以我把我的代码做了这样的修改-->>初始化。
static bool note=YES;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
if(note)
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(getHRImage:)
name:@"DecodeComplete" object:nil]; note=NO;} ->>
- (void) dealloc
{
note=true;
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"DecodeComplete" object:nil];
//[super dealloc];
}现在,addObserver方法只调用了一次,所以我的问题就解决了。谢谢大家的宝贵指导。
发布于 2015-04-20 09:28:55
在ARC环境中不会调用- (void) dealloc。Instread,您可以在添加观察者之前删除它,如下所示:
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"DecodeComplete" object:self];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getHRImage:) name:@"DecodeComplete" object:nil];
}
}https://stackoverflow.com/questions/29743884
复制相似问题