2011-10-09 29 views
2

我試圖把委託和我的tableview的數據源放到一個單獨的類。我的問題是,它總是崩潰,沒有錯誤。這就是爲什麼我無法弄清楚我做錯了什麼。也許有人可以告訴我。也許我使用ARC也很重要。把UITableView和數據源/委託在單獨的類不起作用(XCode 4.2)

所以這是我的簡單的代碼:

//ViewController.h 
@interface ViewController : UIViewController { 
    UITableView *myTableView; 
} 

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

@end 

//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 

//MyTableViewDelegateDatasourceDelegate.h 
@interface MyTableViewDatasourceDelegate : NSObject <UITableViewDataSource, UITableViewDelegate> 

@end 

//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 

回答

6

看來,你是不是引用test anywher否則它會在viewDidLoad方法結束時自動釋放。確保你實現test作爲一個實例變量,所以至少有一些東西引用它。

對象不是必需的,因爲它是持久性的。看看delegate屬性定義:

@property(nonatomic,assign) id <UITableViewDelegate> delegate; 

assign這裏是至關重要的,這意味着這是一個弱引用和UITableView中不會保留該對象。請注意,如果它說(nonatomic, retain)你的代碼可以工作,但是蘋果公​​司的設計決定是這樣實現它以避免保留週期。

+0

很酷,工作!仍然必須習慣這一點。所以這意味着如果我不想立即擺脫它,我就會將某些東西聲明爲實例變量? – MoFuRo

+0

我已經修改了我的答案,但我仍然建議閱讀ARC,因爲可能有其他方法可以解決此問題。 –

相關問題