Imagepair对象是其他类的成员变量。我希望在每次调用getImageURLs-function (请求网页并解析其元素)时更改其成员。第一次运行正常,但是如果我在同一个对象上第二次调用该函数,应用程序就会崩溃,并留下一个EXC_BAC_ACCESS异常。我的猜测是,我在内存管理方面做了一些错误的事情,但我不知道是什么原因,因为我有Java背景,并且不太习惯手动进行内存管理。
@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;
}
}发布于 2011-06-01 20:55:59
在requestImage:中,您可以初始化UIImage,但永远不会释放它。或者将return image更改为return [image autorelease],或者将该方法重命名为newRequestImage:,这样就可以清楚地看到它返回的是一个保留的图像。
https://stackoverflow.com/questions/6201094
复制相似问题