2013-11-25 115 views
1

當我在我的tableview點擊一個細胞,應用程序崩潰與崩潰:的UITableView選擇

enter image description here

// QuestionViewController.h 

@interface QuestionViewController : UIViewController <UITableViewDelegate , UITableViewDataSource> { 
} 

@property (nonatomic, strong) AppDelegate *app; 
@property (nonatomic, retain) PFObject *feed; 
@end 

// QuestionViewController.m 

@synthesize app, feed; 

- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section 
{ 
    return [[feed objectForKey:@"options"] count]; 
} 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
    return 1; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    static NSString *CellIdentifier = @"Cell"; 

    UITableViewCell *cell = (UITableViewCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
    } 

    NSString *cellTxt = [[[feed objectForKey:@"options"] objectAtIndex:indexPath.row] objectForKey:@"option_text"]; 

    [[cell textLabel] setText:cellTxt]; 

    return cell; 

} 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
    NSLog(@"clicked cell"); 
} 

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    app = [[UIApplication sharedApplication]delegate]; 
    feed = [app.feed objectAtIndex:0]; 
} 

我已經實現didSelectRowAtIndexPath方法,但它不會崩潰之前調用。

SO上的其他線程表明我有不連接的網點,但我已檢查過,情況並非如此。

我創建上面的UIViewController的多個實例是這樣的:

for (int a = 0; a < totalQuestions; a++) { 

    QuestionViewController *temp = (QuestionViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"aQuestion"]; 

    temp.view.frame = CGRectMake(self.view.frame.size.width*a+scrollWidthBeforeAppend, 0, 320, 443); 

    [scroller addSubview:temp.view]; 

} 

並將其添加到滾動視圖。它們顯示正確,UITableView被填充,並且除了當我嘗試單擊一個單元格時,一切似乎都正常工作。有什麼建議麼?

+0

您不應將一個控制器的視圖添加到另一個控制器的視圖,而不會將該視圖控制器添加到您將其添加到的視圖控制器的子項中(使用自定義容器視圖控制器api)。 – rdelmar

+0

@rdelmar正在維護一個視圖控制器數組(如下面的答案)一個糟糕的想法/糟糕的設計? – StuR

+1

一般來說這並不是一個壞主意,它可以解決您的直接問題,但正如我在我的評論中所說的那樣,添加另一個控制器的視圖而不讓它成爲孩子並不是一個好主意。如果你這樣做了,父控制器將一個強指針(在它的childViewControllers數組中)保存給子對象,所以不需要創建自己的控制器數組。 – rdelmar

回答

4

當你按下單元格時,你的臨時UIViewControllers被取消分配。 您應該保留對它們的引用以防止出現這種情況,例如在數組中。

+0

曾經閱讀過如此簡單而明顯的解決方案,你不能相信你沒有想到它......這就是這個解決方案。 – iHorse