2012-04-08 151 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中的此对象,而不是首先“拥有”它,以致您的应用程序崩溃。