为什么我的代表变成了零?

时间:2014-10-25 00:17:39

标签: ios objective-c uiviewcontroller delegates protocols

我已经完成了这个代表团模式一百万次。在第一百万次和第一次我得到一个零代表:

CatViewController *vc = [[UIStoryboard storyboardWithName:@"Cat" bundle:nil] instantiateInitialViewController];
vc.delegate = self;
[self presentViewController:vc animated:YES completion:^{
        DDLogWarn(@"[%@ %@] delegate: %@", THIS_FILE, THIS_METHOD, vc.delegate); //here the delegate is valid
    }];

@protocol CatViewControllerDelegate;

@interface CatViewController : UIViewController

@property (weak, nonatomic) id <CatViewControllerDelegate> delegate;

@end

@protocol CatViewControllerDelegate <NSObject>

@required
- (void)catViewController:(CatViewController*)catVC didFinishWithSuccess:(BOOL)success;

@end

但是,在CatViewController的viewDidLoad中,self.delegate已经是nil,当我尝试这样做时当然是nil:

    [self.delegate catViewController:self didFinishWithSuccess:YES];

为什么catViewController的委托变为nil?

3 个答案:

答案 0 :(得分:3)

问题在于CatViewController嵌入在Storyboard的导航控制器中。因此,instantiateInitialViewController没有返回CatViewController,尽管屏幕上的一切都很好。修复:

UINavigationController *navVC = [[UIStoryboard storyboardWithName:@"Cat" bundle:nil] instantiateInitialViewController];
CatViewController *catVC = navVC.viewControllers[0];
catVC.delegate = self;

答案 1 :(得分:2)

你有:

vc.delegate = self;

无论self是什么,它都会在新视图控制器的viewDidLoad被调用时被删除。为了测试这个理论,在该类中放入一个dealloc方法并在其中加入一个断点。

答案 2 :(得分:-2)

您是否尝试过这样声明代理?

@property (unsafe_unretained, nonatomic) id <CatViewControllerDelegate> delegate;