2

我正在做这个 iPhone 项目,我需要在普通视图控制器中有一个(动态)表视图。我没有选择 Table View Controller,因为我需要在页面中放置其他东西。想象一个带有文本字段、按钮和我的大约 4-5 个单元格的小表格视图的页面。

当我运行该应用程序时,我需要触摸一个按钮来切换到该视图。我单击按钮,应用程序崩溃并告诉我:

2012-07-22 14:40:57.304 多少?[3055:f803] * -[UITableView _createPreparedCellForGlobalRow:withIndexPath:]、/SourceCache/UIKit_Sim/UIKit-1914.84/UITableView.m:6061 中的断言失败

这是我的 .H 文件:

#import <UIKit/UIKit.h>

@interface ProjectViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>

@end

这是我的 .M 文件:

#import "ProjectViewController.h"

@interface ProjectViewController ()

@end

@implementation ProjectViewController


//MyViewController.m
#pragma mark - Table View Data Source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    NSLog(@"numberOfSectionsInTableView");
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSLog(@"numberOfRowsInSection");
    return 5;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"cellForRowAtIndexPath");

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];

    NSLog(@"cellForRowAtIndexPath");

    cell.textLabel.text = @"Test";

    return cell;
}


@end

我从表视图控制拖动到我的控制器来设置委托和数据源。

我做错了什么??

谢谢你的帮助。

4

2 回答 2

2

尝试在您的.h文件中制作一个插座并将其连接到tableView您的storyboard

项目视图控制器.h

@property (nonatomic, strong) IBOutlet UITableView *myTableView;

项目视图控制器.m

@synthesize myTableView;

...

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"cellForRowAtIndexPath");

    UITableViewCell *cell = [self.myTableView dequeueReusableCellWithIdentifier:@"cell"];

    NSLog(@"cellForRowAtIndexPath");

cell.textLabel.text = @"Test";

return cell;

}

于 2012-07-22T19:31:36.627 回答
0

在你的 -cellForRowAtIndexPath 中,如果你这样做,你会没事的。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(@"cellForRowAtIndexPath");

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];

if(cell == nil)
{
    cell = [[UITableViewCell alloc] 
             initWithStyle:UITableViewCellStyleDefault 
             reuseIdentifier:@"cell"];
}

NSLog(@"cellForRowAtIndexPath");

cell.textLabel.text = @"Test";

return cell;

}

问题是您的单元从未分配和初始化内存。这就是你得到错误的原因。

于 2012-07-23T14:44:54.707 回答