我在我的应用程序中实现了NSNotificationCenter.我在完成图像解码时发送通知.第一次图像解码将完成8次.所以通知假设发送8次.但它调用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];
}
解决方法
解:
我重新检查了我的代码,initWithFrame:(CGRect)框架调用了8次,并添加了8次NSNotification观察器.
我重新检查了我的代码,initWithFrame:(CGRect)框架调用了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方法只调用一次,所以我的问题解决了.谢谢大家的宝贵指导.