MoF*_*uRo 2 xcode objective-c uitableview
我试图将我的tableview的委托和数据源放入一个单独的类中.我的问题是它总是崩溃而没有错误.这就是为什么我无法弄清楚我做错了什么.也许有人可以告诉我.也许我使用ARC也很重要.
这就是我的简单代码:
//ViewController.h
@interface ViewController : UIViewController {
UITableView *myTableView;
}
@property (strong, nonatomic) IBOutlet UITableView *myTableView;
@end
Run Code Online (Sandbox Code Playgroud)
//ViewController.m
#import "ViewController.h"
#import "MyTableViewDatasourceDelegate.h"
@implementation ViewController
@synthesize myTableView;
- (void)viewDidLoad
{
[super viewDidLoad];
MyTableViewDatasourceDelegate *test = [[MyTableViewDatasourceDelegate alloc] init];
self.myTableView.delegate = test;
self.myTableView.dataSource = test;
}
@end
Run Code Online (Sandbox Code Playgroud)
//MyTableViewDelegateDatasourceDelegate.h
@interface MyTableViewDatasourceDelegate : NSObject <UITableViewDataSource, UITableViewDelegate>
@end
Run Code Online (Sandbox Code Playgroud)
//MyTableViewDatasourceDelegate.m
@implementation MyTableViewDatasourceDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
}
cell.textLabel.text = @"Test";
return cell;
}
@end
Run Code Online (Sandbox Code Playgroud)
您似乎没有test在其他任何地方引用它,因此它会在viewDidLoad方法结束时自动释放.确保你实现test为一个实例变量,所以至少有一些东西引用它.
对象不需要是ivar才能持久存在.看一下delegate属性定义:
@property(nonatomic,assign) id <UITableViewDelegate> delegate;
Run Code Online (Sandbox Code Playgroud)
在assign这里是至关重要的,这意味着这是一个弱引用和UITableView中不会保留该对象.请注意,如果它说(nonatomic, retain)您的代码可以正常工作,那么Apple的设计决定是以这种方式实现它以避免保留周期.
| 归档时间: |
|
| 查看次数: |
5628 次 |
| 最近记录: |