【问题标题】:ContainerViewController delegate to ChildViewControllerContainerViewController 委托给 ChildViewController
【发布时间】:2015-05-11 04:15:08
【问题描述】:

ContainerViewController 将方法-delegateMethod 委托给ChildViewController
但在下面的代码中,-delegateMethod 没有被调用。
我想是因为_childViewController已经发布了。
如何修复它以使其运行-delegateMethod

ContainerViewController.h

@protocol ContainerViewDelegate <NSObject>

- (void)delegateMethod;

@end

@interface ContainerViewController : UIViewController

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

@end

ContainerViewController.m

@interface ContainerViewController () {
    ChildViewController *_childViewController;
}

//...

- (void)viewDidLoad
{
    _childViewController = [[WeeklyViewController alloc]init];
    [self addChildViewController:_childViewController];
    [self.view addSubview:_childViewController.view];
    [_childViewController didMoveToParentViewController:self];
}

- (void)buttonAction {
    [self.delegate delegateMethod];
}

ChildViewController.m

@interface ChildViewController () <ContainerViewDelegate>

//...

- (void)delegateMethod {
    NSLog(@"succeed!");
}

【问题讨论】:

  • _childViewController 没有被释放。当您将 ContainerViewController 添加为子项时,它会获得一个指向它的强指针。

标签: ios objective-c uiviewcontroller delegates


【解决方案1】:

您从未设置委托,因此 self.delegate 将为 nil。你应该这样做,

    - (void)viewDidLoad
{
    _childViewController = [[WeeklyViewController alloc]init];
    self.delegate = _childViewController;
    [self addChildViewController:_childViewController];
    [self.view addSubview:_childViewController.view];
    [_childViewController didMoveToParentViewController:self];
}

【讨论】:

    猜你喜欢
    • 2016-05-01
    • 2016-05-01
    • 1970-01-01
    • 2018-05-07
    • 1970-01-01
    • 2023-03-04
    • 2020-03-05
    • 2012-01-21
    • 1970-01-01
    相关资源
    最近更新 更多