Ios 为什么单元格中的init方法获胜';发生dequeueReusableCellWithIdentifier时未调用

Ios 为什么单元格中的init方法获胜';发生dequeueReusableCellWithIdentifier时未调用,ios,objective-c,uitableview,Ios,Objective C,Uitableview,我的代码是这样的 viewcontroller.m - (void)viewDidLoad { [super viewDidLoad]; UITableView *tableView = [[UITableView alloc] init]; tableView.delegate = self; tableView.dataSource = self; [tableView registerClass:[TableViewCell class] for

我的代码是这样的

viewcontroller.m

- (void)viewDidLoad {
    [super viewDidLoad];

    UITableView *tableView = [[UITableView alloc] init];

    tableView.delegate = self;
    tableView.dataSource = self;
    [tableView registerClass:[TableViewCell class] forCellReuseIdentifier:@"cell"];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.textLabel.text = @"Hello, world";
    cell.delegate = self;
    return cell;
}

手机

- (void)awakeFromNib {
    [super awakeFromNib];
    [self commonInit];
    // Initialization code
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self commonInit];
    }
    return self;
}

- (void)commonInit
{
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress)];
    [self addGestureRecognizer:longPress];
}


- (void)longPress
{
    [self.delegate actionTriggered:self];
}

所以屏幕显示一个只有一个单元格的tableview,其中包含“hello world” 当使用长按手势时,什么也没发生

所以我在commonInit中设置了一个断点。 发现此方法未被调用。 不知道为什么。以及如何修复它。
感谢您的帮助。

在“viewDidLoad”中,您创建了一个局部变量“tableView”。一旦方法完成,该变量就会超出范围

这不行

假设viewcontroller.m文件中的类继承自UITableViewController,则只需确保配置现有tableView属性,而不是创建局部变量:

-(void)viewDidLoad {
    [super viewDidLoad];

    // UITableView *tableView = [[UITableView alloc] init];  <-- Don't!

    tableView.delegate = self;
    tableView.dataSource = self;
    [tableView registerClass:[TableViewCell class] forCellReuseIdentifier:@"cell"];
}
-(void)viewDidLoad{
[超级视图下载];

//UITableView*tableView=[[UITableView alloc]init];因为您注册了一个类,所以它应该调用`initWithStyle:reuseIdentifier:`.Cf.讨论