为什么我的自定义代表不工作?

时间:2011-09-08 21:42:59

标签: objective-c ios delegates uinavigationcontroller

我正在尝试构建一个委托,允许我将子视图控制器中的数据传递给父级。我一直在网上查看各种教程/问题,但我的委托方法没有被触发。

你能看看我下面的代码,看看我是否遗漏了什么?

TownListViewController.h

@protocol TownListViewControllerDelegate;

@interface TownListViewController : UITableViewController <NSFetchedResultsControllerDelegate> {

    id <TownListViewControllerDelegate> delegate;

}

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

@end

@protocol TownListViewControllerDelegate
@optional

- (void)didSelectTown:(Town *)town;

@end

TownListViewController.m

@implementation TownListViewController

@synthesize delegate;

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [delegate didSelectTown:(Town *)[self.fetchedResultsController objectAtIndexPath:indexPath]];
    [self.navigationController popViewControllerAnimated:YES];
}

@end

SearchViewController.h

@interface SearchViewController : UITableViewController <TownListViewControllerDelegate> {

...

}

SearchViewController.m

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    TownListViewController * townViewController = [[TownListViewController alloc] initWithNibName:@"TownListViewController" bundle:nil];
    townViewController.delegate = self;
    [self.navigationController pushViewController:townViewController animated:YES];
}

- (void)didSelectTown:(Town *)town
{
    NSLog(@"didSelectTown fired");
    self.selectedTown = town;
}

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

设置委托后尝试重新加载数据。我认为第一次调用表的reloadData发生在TownListViewController的initWithNibName期间......无论如何,你可以在这个方法上发布delegate值:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

我打赌是没有......

顺便说一句,检查变量delegate是否符合协议是一种很好的做法,尝试添加此行,假设该方法是可选的:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if([delegate conformsToProtocol(TownListViewControllerDelegate)] && [delegate respondsToSelector:@selector(didSelectTown:objectAtIndexPath:)])
        [delegate didSelectTown:(Town *)[self.fetchedResultsController objectAtIndexPath:indexPath]];
    [self.navigationController popViewControllerAnimated:YES];
}