在下面的方法中,我在包含「urlString」變量的行上收到「EXC_BAD_ACCESS」。我的研究表明,當程序向已發佈的變量發送消息時會發生此錯誤。但是因爲我使用的是ARC,所以我不會手動釋放內存。我怎樣才能防止ARC過早釋放這個變量?ARC下的EXC_BAD_ACCESS內存錯誤
-(NSMutableArray *)fetchImages:(NSInteger *)count {
//prepare URL request
NSString *urlString = [NSString stringWithFormat:@"http://foo.example.com/image?quantity=%@", count];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
//Perform request and get JSON as a NSData object
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//Parse the retrieved JSON to an NSArray
NSError *jsonParsingError = nil;
NSArray *imageFileData = [NSJSONSerialization JSONObjectWithData:response options:0 error:&jsonParsingError];
//Create an Array to store image names
NSMutableArray *imageFileNameArray;
//Iterate through the data
for(int i=0; i<[imageFileData count];i++)
{
[imageFileNameArray addObject:[imageFileData objectAtIndex:i]];
}
return imageFileNameArray;
}
謝謝卡爾。糾正兩點。使用%d修復了內存錯誤。我現在正在閱讀格式字符串,以便我將來不會再犯同樣的錯誤。並沒有理由像我那樣使用指針。我的代碼現在匹配你的#2。 – hughesdan 2012-08-05 04:23:40
清潔和簡單的答案+1 – sridvijay 2012-08-05 04:24:45
@hughesdan,幾乎所有的格式字符串都與'printf'中的相同。這只是爲了使用對象而添加的「%@」。 – 2012-08-05 04:25:13