Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Objective c 尝试通过viewWithTag获取UIImageView引用后崩溃_Objective C_Ios_Uiimageview_Exc Bad Access - Fatal编程技术网

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

Objective c 尝试通过viewWithTag获取UIImageView引用后崩溃,objective-c,ios,uiimageview,exc-bad-access,Objective C,Ios,Uiimageview,Exc Bad Access,我需要在表格单元格中绘制图像。到目前为止,在创建视图并将其分配给单元格后,我还无法获得对UIImageView的正确引用。例如,同样的过程也适用于UILabel 我不知道我做错了什么 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cel

我需要在表格单元格中绘制图像。到目前为止,在创建视图并将其分配给单元格后,我还无法获得对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
变量的范围。如果单元格还不存在,则创建一个新的
UIImageView
,该视图仅存在于if块中。它隐藏先前声明的变量,并在if块结束后消失。 而不是

UIImageView *imageView = ...
你应该简单地写

imageView = ...

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

非常感谢!我对Objective-C的作用域和内部工作仍有点模糊。