2012-08-05 61 views
0

在下面的方法中,我在包含「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; 

} 

回答

6

您的問題與ARC無關。 NSInteger不是一個類,所以你不想使用%@格式。 %@將發送一個description方法到系統認爲是一個對象,但事實證明它不是一個 - CRASH。爲了解決你的問題,你有兩個選擇:

  1. 你可能想:

    NSString *urlString = 
        [NSString stringWithFormat:@"http://foo.example.com/image?quantity=%d", 
         *count]; 
    

    確保count指針是有效的第一!

  2. 您可能需要改變你的方法簽名是:

    -(NSMutableArray *)fetchImages:(NSInteger)count; 
    

    ,然後改變urlString行,如下所示:

    NSString *urlString = 
        [NSString stringWithFormat:@"http://foo.example.com/image?quantity=%d", 
         count]; 
    

    您還需要修復所有呼叫者以匹配新的簽名。

第二個選項對我來說似乎更「正常」,但沒有更多的程序,就不可能更具體。

+0

謝謝卡爾。糾正兩點。使用%d修復了內存錯誤。我現在正在閱讀格式字符串,以便我將來不會再犯同樣的錯誤。並沒有理由像我那樣使用指針。我的代碼現在匹配你的#2。 – hughesdan 2012-08-05 04:23:40

+0

清潔和簡單的答案+1 – sridvijay 2012-08-05 04:24:45

+2

@hughesdan,幾乎所有的格式字符串都與'printf'中的相同。這只是爲了使用對象而添加的「%@」。 – 2012-08-05 04:25:13

2

,你可能還需要alloc和添加對象之前初始化的

NSMutableArray *imageFileNameArray; 

,否則你會保持崩潰。所以你會有

//Create an Array to store image names 

NSMutableArray *imageFileNameArray = [[NSMutableArray alloc] init]; 
+0

+1好抓Dade。謝謝! – hughesdan 2012-08-05 15:50:33