0

I am trying to implement programmatically a UITableView.

I have a UIView (named IndexView). Here is the constructor :

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) 
    {
        MyTableViewController* favorite_table_view_controller = [[MyTableViewController alloc] init];
        UITableView* theTableView = [[UITableView alloc] initWithFrame:CGRectMake(20, 65, 280, 350) style:UITableViewStylePlain];
        theTableView.delegate = favorite_table_view_controller;
        theTableView.dataSource = favorite_table_view_controller;
        [self addSubview:theTableView];
    }
    return self;
}

MyTableViewController is defined this way :

@interface MyTableViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>

And implements the two necessary functions :

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return data.count;
}

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

    if (cell == nil)
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"Cell"];

    [cell.textLabel setText:[data objectAtIndex:indexPath.row]];

    return cell;
}

And I get this error :

[__NSMallocBlock__ tableView:numberOfRowsInSection:]: unrecognized selector sent to instance 0x6897de0
2012-07-18 12:07:24.607 ButtonsTest[22854:f803] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSMallocBlock__ tableView:numberOfRowsInSection:]: unrecognized selector sent to instance 0x6897de0'

I think there is a problem when I'm binding the controller to the view. But I can't find where.

Any idea where does the problem come from ?

4

1 回答 1

0

您不应该从视图构建视图控制器。应该反过来做。(从 UIVIewControllers 构造视图)

制作一个 ViewController 的子类UIViewController,然后让它实现UITableViewDelegateand UITableViewDataSource。如果您仍然需要从另一个控制器类控制 UITableView,请在 parent 中设置此连接UIViewController,而不是从 View 本身。这就是iOS密集使用MVC的基本前提

于 2012-07-18T10:33:19.177 回答