iphone - iOS - 无法访问 didSelectRowAtIndexPath 中的 NSMutableArray?

标签 iphone ios nsmutablearray exc-bad-access

我无法在 didSelectRowAtIndexPath 中访问我的 NSMutableArray,尽管我可以在 cellForRowAtIndexPath 中访问它。

这是我的代码:-

- (void)viewDidLoad
{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"drinks" ofType:@"plist"];
    self.drinkArray = [[NSMutableArray alloc] initWithContentsOfFile:path];
    NSLog(@"%@", self.drinkArray);
    [super viewDidLoad];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    NSLog(@"I am inside cellForRowAtIndexPath");
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    // Configure the cell.
    NSDictionary *dict = [self.drinkArray objectAtIndex:indexPath.row];
    cell.textLabel.text = [dict objectForKey:@"name"]; 
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    [dict release];
    return cell;
}

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

    DrinkDetails *detailViewController = [[DrinkDetails alloc] initWithNibName:@"DrinkDetails" bundle:nil];
    // ...
    // Pass the selected object to the new view controller.
    //detailViewController.drink = [self.drinkArray objectAtIndex:indexPath.row];

    NSLog(@"%@", self.drinkArray);

    [self.navigationController pushViewController:detailViewController animated:YES];
    [detailViewController release];

}

有时 NSLog 打印一些愚蠢的输出,有时它给我一个错误“EXC_BAD_ACCESS”。

请看一下我的代码有什么问题。

如有任何帮助,我们将不胜感激。

谢谢。

最佳答案

您有一个(实际上是两个)问题,但主要问题在您的 -cellForRowAtIndexPath: 方法中:

[dict release];

去掉这一行,它应该可以正常工作。

之所以解决您的问题是因为 -objectAtIndex: 只是返回一个指向内存中所请求对象的指针,因此您不会(也不应该)发送-release 消息发送给该对象,因为 NSArray 在插入对象时获得了该对象的所有权。将 -release 发送到此对象引用有效地释放了内存中的对象,现在 NSArray 中的此索引指向垃圾内存。 坏坏坏

另一个问题是你这里有内存泄漏:

self.drinkArray = [[NSMutableArray alloc] initWithContentsOfFile:path];

您正在将 -retain 消息发送到您已经通过发送 -alloc 拥有所有权的对象引用。 (这当然假设您的 @property 具有 retain setter 修饰符)

要解决此问题,只需将 -autorelease 消息发送到此实例即可:

self.drinkArray = [[[NSMutableArray alloc] initWithContentsOfFile:path] autorelease];

关于iphone - iOS - 无法访问 didSelectRowAtIndexPath 中的 NSMutableArray?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7626004/

相关文章:

iphone - ScrollView ContentOffset 和 ZoomScale

ios - 如何在 iOS UIWebView 中禁用谷歌地图移动网站广告?

ios - 根据标签大小调整 UICollectionViewCell 的大小

ios - 无法将 RestKit 0.2 获取到 POST 参数

objective-c - 来自 removeObjectsInRange : but passed range is within bounds 的 NSRangeException

ios - 如何在 Objective-C 中将一个 NSMutableArray 存储到另一个 NSMutableArray

iOS CBPeripheral 连接问题

iOS 应用程序 - 为什么要包含 @2x 和低分辨率图像?

ios - 我如何绘制一个带有角半径的三角形?

ios - 在 json 数据中添加 InvoicID 新键和值