I have a view controller with this method:
- (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];
}
}
}
}
And ImagesDownloader
is an NSObject
subclass like this:
@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
In turn, GetImage
is another NSObject
subclass that calls a RESTful web service by using an NSURLConnection
object, and then, in its connectionDidFinishLoading:
delegate method, it posts the notification the imagesDownloader
object is observing via Notification Center:
[[NSNotificationCenter defaultCenter] postNotificationName:@"getImageDidFinish"
object:nil
userInfo:serviceInfoDict];
This is the call where I sometimes get the EXC_BAD_ACCESS error.
The scenario is like this: the view controller is loaded (it is pushed into a navigation stack) and getImages
is called. Right now, its self.myEntities
has 3 objects, so self.imagesDownloader
is initialized and call 3 times to getImageFromServiceUrl
. The service is called 3 times as well, and in connectionDidFinishLoading:
, the notification is posted the 3 times with no error.
But I then go back and forth the view controller, and it is loaded again and same calls made. But this time, I get the error the 2nd time the notification is going to be posted from connectionDidFinishLoading:
. I don't undersatnd why, what could I be missing?
Thanks in advance