Iphone 设置UITableView委托和数据源

Iphone 设置UITableView委托和数据源,iphone,objective-c,uitableview,delegates,Iphone,Objective C,Uitableview,Delegates,这是我的问题: 我的故事板中有一个小的UITableView: 这是我的代码: SmallTableViewController.h #import <UIKit/UIKit.h> #import "SmallTable.h" @interface SmallViewController : UIViewController @property (weak, nonatomic) IBOutlet UITableView *myTable; @end #import <

这是我的问题: 我的故事板中有一个小的
UITableView

这是我的代码:

SmallTableViewController.h

#import <UIKit/UIKit.h>
#import "SmallTable.h"

@interface SmallViewController : UIViewController

@property (weak, nonatomic) IBOutlet UITableView *myTable;

@end
#import <Foundation/Foundation.h>

@interface SmallTable : NSObject <UITableViewDelegate , UITableViewDataSource>

@end
现在您可以看到,我想将一个名为myTableDelegate的实例设置为myTable的委托和数据源

这是SmallTable类的源代码

SmallTable.h

#import <UIKit/UIKit.h>
#import "SmallTable.h"

@interface SmallViewController : UIViewController

@property (weak, nonatomic) IBOutlet UITableView *myTable;

@end
#import <Foundation/Foundation.h>

@interface SmallTable : NSObject <UITableViewDelegate , UITableViewDataSource>

@end
我实现了应用程序需要的所有
UITableViewDelegate
UITableViewDataSource
方法。为什么它会在视图出现之前崩溃


谢谢

您大概在使用ARC?您的
myTableDelegate
仅在
viewDidLoad
中的局部变量中引用——一旦该方法结束,它将被释放。(在委托/数据源模式中,对象不拥有自己的委托,因此表视图对对象的引用很弱。)我不认为这会单独导致崩溃,但这可能是问题的关键。

setDelegate
不会保留委托


numberOfsectionsTableView
方法必须返回1而不是0

里克斯特是对的。但是我想您需要为您的属性使用
strong
限定符,因为在
viewDidLoad
方法的末尾,对象将被释放

@property (strong,nonatomic) SmallTable *delegate;

// inside viewDidload

[super viewDidLoad];
self.delegate = [[SmallTable alloc] init];    
[self.myTable setDelegate:myTableDelegate];
[self.myTable setDataSource:myTableDelegate];
但是否有任何理由对表使用单独的对象(数据源和委托)?为什么不将
SmallViewController
设置为表的源和委托

此外,您没有以正确的方式创建单元格。这些行没有任何作用:

static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

// Configure the cell...
cell.textLabel.text = @"Hello there!";
dequeueReusableCellWithIdentifier
只需从表“cache”中检索一个已创建且可重用(这是为了避免内存消耗)但尚未创建的单元格

您在哪里执行alloc init?改为这样做:

static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(!cell) {
    cell = // alloc-init here
}
// Configure the cell...
cell.textLabel.text = @"Hello there!";
此外,对
numberOfSectionsInTableView
说,返回1而不是0:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

UITableView对象的委托必须采用UITableViewDelegate协议。协议的可选方法允许代理管理选择,配置节标题和页脚,帮助删除方法


节数应至少设置一个

您是否也可以添加崩溃日志?查看线程中的讨论-@Marco Manzoni:您找到解决方案了吗?好的,我刚刚创建了一个新的@property(弱,非原子)SmallTable*委托;现在应用程序没有崩溃,但是。。。表视图是空的!我不明白为什么。。。
(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 0;
}