2013-11-25 112 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