The Imagepair object is a member variable of some other class.. I want its members to be changed, every time I call the getImageURLs-function (requests a web page and parses its elements). The first time it works fine, but if I call the function a 2nd time on the same object, the application crashes and leaves me with a EXC_BAC_ACCESS Exception. My guess is, that I am doing something wrong with the memory management, but I cannot figure out what, as I’ve got a background in Java and am not really used to doing the memory management manually.
@implementation Imagepair
@synthesize imageLeft;
@synthesize imageRight;
@synthesize imageURLLeft;
@synthesize imageURLRight;
@synthesize idLeft;
@synthesize idRight;
//get random imagepair link
- (void) getImageURLs{
NSLog(@"Get random imagepair from server");
NSError *error = nil;
NSURL *url = [NSURL URLWithString:cSERVER_GET_RANDOM_IMAGE];
ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:url];
[request startSynchronous];
//init HTML-parser
HTMLParser *parser = [[HTMLParser alloc] initWithString: [request responseString] error:&error];
//check for error
if (error) {
NSLog(@"Error: %@", error);
}
//get body-node
HTMLNode *bodyNode = [parser body];
//get all link-nodes
HTMLNode *success = [bodyNode findChildTag:@"success"];
HTMLNode *imgurl1 = [success findChildTag:@"imgurl1"];
HTMLNode *imgurl2 = [success findChildTag:@"imgurl2"];
HTMLNode *imgid1 = [success findChildTag:@"imgid1"];
HTMLNode *imgid2 = [success findChildTag:@"imgid2"];
HTMLNode *imgvotes1 = [success findChildTag:@"imgvotes1"];
HTMLNode *imgvotes2 = [success findChildTag:@"imgvotes2"];
//read content and set members
[self setImageURLLeft:[imgurl1 contents]];
[self setImageURLRight:[imgurl2 contents]];
votesLeft = [[imgvotes1 contents] intValue];
votesRight = [[imgvotes2 contents] intValue];
[self setIdLeft:[imgid1 contents]];
[self setIdRight:[imgid2 contents]];
[self setImageLeft:[self requestImage:imageURLLeft]];
[self setImageRight:[self requestImage:imageURLRight]];
[request release];
[parser release];
}
//returns an UIImage for an URL
-(UIImage *)requestImage:(id)url{
NSURL *imgURL = [NSURL URLWithString:url];
NSData *data = [NSData dataWithContentsOfURL:imgURL];
UIImage *image = [[UIImage alloc] initWithData:data];
return image;
}
}
In
requestImage:you initialize anUIImagebut never release it. Either changereturn imagetoreturn [image autorelease]or rename the method tonewRequestImage:so that it is clear that it returns a retained image.