为什么不能调用委托的方法

时间:2012-08-14 06:19:09

标签: ios delegates uistoryboard

文件:PeopleLinkEditViewController.h

@protocol  PeopleLinkEditViewControllerDelegate<NSObject>
@optional
-(void)headerInfoEditFinish;

@end
@interface PeopleLinkEditViewController : UITableViewController
{
    id<PeopleLinkEditViewControllerDelegate> delegate;
}

@property (nonatomic, retain) id<PeopleLinkEditViewControllerDelegate> delegate;
-(IBAction)doneEdit:(id)sender;

@end

文件:PeopleLinkEditViewController.m


@implementation PeopleLinkEditViewController
...
@synthesize delegate = _delegate;
...
- (void)viewDidLoad
{
...
headerView = [[PeopleLinkHeaderView alloc] initWithFrame:CGRectMake(0, 0, 320, 286)
                                                    passData:headerDic];
...
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if(section == 0)
    {
        return headerView;
    }

    return nil;
}
-(IBAction)doneEdit:(id)sender
{      
    if ([delegate respondsToSelector:@selector(headerInfoEditFinish)])
    {
        NSLog(@"%d", __LINE__);
        [delegate headerInfoEditFinish];
    }
}
@end

文件:PeopleLinkHeaderView.h

#import "PeopleLinkEditViewController.h"

@interface PeopleLinkHeaderView : UIView<PeopleLinkEditViewControllerDelegate>
{

}
@end

文件:PeopleLinkHeaderView.m

@interface PeopleLinkHeaderView()

@property (nonatomic, retain) PeopleLinkEditViewController *edit;

@end

@implementation PeopleLinkHeaderView

- (id)initWithFrame:(CGRect)frame passData:(NSDictionary *)data
{
    UIStoryboard*  sb = [UIStoryboard storyboardWithName:@"MainStoryboard"
                                                  bundle:nil];
    PeopleLinkEditViewController *edit = [sb instantiateViewControllerWithIdentifier:@"PeopleLinkEditController"];
    edit.editDelegate = self;
}

-(void)headerInfoEditFinish
{
    [baseInfo setValue:baseInfoValue forKey:@"value"];
    [dataPass writeHeaderValueToPlist:baseInfo];
} 

无法调用委托方法。当我调试它时,我发现委托在editcontroller中是nil。和editcontroller是由storyboard创建的。 Headerview是编辑控制器的子视图。

1 个答案:

答案 0 :(得分:3)

问题是您发送操作的实例和您声明该代理的实例不相同。

我可以看一下这个

edit = [[PeopleLinkEditViewController alloc] init];
edit.delegate = self;

这是一个新创建的实例,您不会以任何方式显示或呈现它。也许这是在故事板上形成一个不同的View Controller?如果它是您在故事板中指定的那个,则应该检索一个并分配其代理。

使用此方法检索正确的实例

#import ViewController.h

然后在您要设置委托的地方。

ViewController *tmp = [[self storyboard] instantiateViewControllerWithIdentifier:@"ViewControllerIdentifier"];
tmp.delegate = self;

别忘了更改为包含该类的标题并更改为正确的标记。

取自此处:

https://stackoverflow.com/a/11931714/1068522