异常类型:EXC_BAD_ACCESS(SIGBUS)

时间:2011-06-01 12:25:06

标签: iphone objective-c memory-management exc-bad-access

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;
    }
}

1 个答案:

答案 0 :(得分:3)

requestImage:中,您初始化UIImage但从未发布它。将return image更改为return [image autorelease]或将方法重命名为newRequestImage:,以便明确返回保留的图像。