开发者

Why isn't my custom delegate working?

开发者 https://www.devze.com 2023-04-03 10:34 出处:网络
I\'m trying to build a delegate to allow me to pass data form a child view controller to the parent. I\'ve been looking at various tutorials / questions online but my delegate method isn\'t being trig

I'm trying to build a delegate to allow me to pass data form a child view controller to the parent. I've been looking at various tutorials / questions online but my delegate method isn't being triggered.

Could you take a look at my code below and see if I'm missing anything?

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 objectAtInd开发者_C百科exPath: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;
}

Any help is much appreciated.


try to reloadData after set the delegate. I think the first call to reloadData of table occurs during the initWithNibName of the TownListViewController... Anyway can you post the delegate value on this method:

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

I bet is nil...

By the way is a good practice to check if the variable delegate conforms the protocol, try adding this line under supposing that the method is optional:

- (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];
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号