objective-c - 尝试通过 viewWithTag 获取 UIImageView 引用后崩溃

标签 objective-c ios uiimageview exc-bad-access

我需要在表格单元格中绘制图像。到目前为止,在创建 View 并将其分配给单元格后,我无法正确引用 UIImageView。例如,相同的过程适用于 UILabel。

我不知道我做错了什么。

- (UITableViewCell *)tableView:(UITableView *)tableView 
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UIImageView *imageView;
    UILabel *title;
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
                                       reuseIdentifier:CellIdentifier] autorelease];

        // Setup title
        title = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)] autorelease];
        title.tag = 1;
        [cell.contentView addSubview:title];

        // Setup image
        UIImageView* imageView = [[[ UIImageView alloc] initWithFrame: 
                                   CGRectMake(50, 0, 50, 50)] autorelease];
        imageView.tag = 2;
        [cell.contentView addSubview:imageView];

    } else {
        // Get references to cell views
        title = (UILabel *)[cell.contentView viewWithTag:1];
        imageView = (UIImageView *)[cell.contentView viewWithTag:2];
    }

    NSLog(@"%@", [title class]);     // UILabel
    NSLog(@"%@", [imageView class]); // CRASH! EXC_BAD_ACCESS

    return cell;
}

最佳答案

问题是 imageView 变量的范围。如果该单元格尚不存在,您可以创建一个仅存在于 if block 中的新 UIImageView。它隐藏了您之前声明的变量,并在 if block 结束后消失。 而不是

UIImageView *imageView = ...

你应该简单地写

imageView = ...

否则,您将创建一个与您在方法顶部声明的对象无关的新对象,并且原始 imageView 仍未定义。

关于objective-c - 尝试通过 viewWithTag 获取 UIImageView 引用后崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5983346/

相关文章:

ios - UISegmentedControl 自定义在 ios 7 中不起作用

objective-c - 为什么我不能在 NSKeyedArchiver 中对 NSValue 进行编码?

ios - 错误域=NSURLErrorDomain 代码=-1000 "bad URL"

java - 2d手游开发: OpenGL ES 2. 0还是cocos2d-x?

ios - 使用来自网络的图像更新 iOS 应用程序

objective-c - 使用 CGAffineTransformMakeRotation 以相同的中心点旋转 UIImageView

ios - Storyboard应用程序中丢失的导航按钮

iphone - UICollectionView 动画(插入/删除项目)

ios - 如何防止像 iPhone 照片应用程序那样自动旋转?

ios - 如何知道 ios 中另一个 View 类中一个 View Controller 的 ImageView 的 x、y 坐标和宽度、高度?