2012-04-08 156 views
0

因此,目前我試圖保存一個indexPath並訪問它,但我不斷收到EXC_BAD_ACCESS錯誤,並且當我在xcode中使用分析工具時,它表示在其索引期間存儲到我的indexPath的值初始化從不讀取。任何人都可以幫助並告訴我這裏出了什麼問題嗎?NSIndexPath內存管理問題

方法來設置indexPath:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 

NSURL *requestURL = [[NSURL alloc] initWithString:@"URL"]; 

//The request 
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:requestURL]; 

request.userInfo = [NSDictionary dictionaryWithObjectsAndKeys:indexPath,@"indexPath", nil]; 

[request setDelegate:self];  

[request startAsynchronous]; 
[requestURL release]; 
[request release]; 
} 

方法來訪問indexPath:

-(void)requestFinished:(ASIHTTPRequest *)request{ 

UIImage *foodImage = [[UIImage alloc] initWithData:[request responseData]]; 

NSIndexPath *indexPath = [request.userInfo objectForKey:@"indexPath"]; 

FoodDescription *detailViewController = [[FoodDescription alloc] initWithNibName:@"FoodDescription" bundle:nil]; 

// pass the food 
detailViewController.aFood = [[NSMutableDictionary alloc] initWithDictionary:[_foodArray objectAtIndex:indexPath.row]]; 
detailViewController.foodPicture = foodImage; 
detailViewController.restaurantName = _restaurantName; 

// Pass the selected object to the new view controller. 
[self.navigationController pushViewController:detailViewController animated:YES]; 
[detailViewController release]; 
} 

回答

2

你正在分配一個NSIndexPath,然後用下一個語句寫下它。更糟糕的是,你泄露了第一條語句中分配的內存。這可能是靜態分析器正在採用的。導致崩潰的原因是您試圖從第一條語句中釋放覆蓋該對象的對象。由於它已經被autoreleased,這個導致崩潰。

只需使用:

NSIndexPath *indexPath = [request.userInfo objectForKey:@"indexPath"]; 

,擺脫發佈聲明。你應該很好。

+0

好吧,你已經解決了indexPath的問題,但由於某種原因它仍然崩潰。我認爲它與userInfo字典有關,但是你有沒有想過爲什麼我還會得到EXC_BAD_ACCESS?我將indexPath代碼更改爲您的建議並擺脫了[indexPath發佈] ... – Apollo 2012-04-08 23:04:04

+0

@ derek.lo您的崩潰仍然發生在同一個地方嗎?你不應該爲了訪問'[request.userInfo objectForKey:@「indexPath」];(儘管它可能會返回nil)而崩潰。 – trudyscousin 2012-04-08 23:06:16

+0

我已經編輯我的帖子,發生崩潰的完整方法。這可能是我將物體從一個視圖轉移到另一個視圖的方式嗎? – Apollo 2012-04-08 23:47:26

0

哦,首先你分配一個新對象,並將其存儲到indexPath。然後,您將這個新分配的索引路徑覆蓋,並將您以前存儲在didSelectRowAtIndexPath中的索引路徑覆蓋。因此,您新分配的索引路徑會丟失,並且會出現錯誤。

更重要的是,您然後嘗試釋放您存儲在didSelectRowAtIndexPath中的此對象,而不是首先「擁有」它,以致您的應用程序崩潰。