使用通知中心

时间:2015-11-11 12:57:56

标签: ios nsurlconnection exc-bad-access nsnotificationcenter

我有一个使用此方法的视图控制器:

- (void)getImages
{
   if (self.myEntities != nil) {
      if (self.myEntities.count > 0) {
         if (self.imagesDownloader == nil) {
            self.imagesDownloader = [[ImagesDownloader alloc] initWithListener];
         }
      }

      for (MyEntity *myEntity in self.myEntities) {
         if (![myEntity.imageUrl isEqualToString:@""] && (myEntity.imageUrl != nil)) {
            [self.imagesDownloader getImageFromServiceUrl:myEntity.imageUrl];
         }
      }
   }
}

ImagesDownloaderNSObject这样的子类:

@implementation ImagesDownloader

- (id)initWithListener
{
   self = [super init];
   if (self) {
      [self registerNotifications];
   }
   return self;
}

- (void)registerNotifications
{
   [[NSNotificationCenter defaultCenter] removeObserver:self
                                                   name:@"getImageDidFinish"
                                                 object:nil];
   [[NSNotificationCenter defaultCenter] addObserver:self
                                            selector:@selector(getImageDidFinish:)
                                                name:@"getImageDidFinish"
                                              object:nil];
}

- (void)getImageFromServiceUrl:(NSString *)imageUrl
{
   GetImage *getImage = [[GetImage alloc] init];
   [getImage queryServiceWithImageUrl:imageUrl];
}

// More instance methods

@end

反过来,GetImage是另一个NSObject子类,它使用NSURLConnection对象调用RESTful Web服务,然后在其connectionDidFinishLoading:委托方法中发布imagesDownloader对象通过通知中心观察的通知:

[[NSNotificationCenter defaultCenter] postNotificationName:@"getImageDidFinish"
                                                    object:nil
                                                  userInfo:serviceInfoDict];

这是我有时会收到EXC_BAD_ACCESS错误的电话。

场景是这样的:加载视图控制器(将其推入导航堆栈)并调用getImages。现在,它的self.myEntities有3个对象,因此初始化self.imagesDownloader并向getImageFromServiceUrl调用3次。该服务也被调用了3次,在connectionDidFinishLoading:中,通知被发布3次而没有错误。

但是我然后来回查看控制器,它再次加载并进行相同的调用。但这一次,我第二次从connectionDidFinishLoading:发布通知时收到错误。我不会理解为什么,我能错过什么?

提前致谢

1 个答案:

答案 0 :(得分:0)

正如@PhillipMills所说,将其添加到ImagesDownloader似乎可以解决问题:

- (void)dealloc
{
   [[NSNotificationCenter defaultCenter] removeObserver:self];
}