我有一个使用此方法的视图控制器:
- (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];
}
}
}
}
ImagesDownloader
是NSObject
这样的子类:
@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:
发布通知时收到错误。我不会理解为什么,我能错过什么?
提前致谢
答案 0 :(得分:0)
正如@PhillipMills所说,将其添加到ImagesDownloader
似乎可以解决问题:
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}