协议不响应选择器

Protocol does not responds to selector

我对 Objective-C 协议有疑问。

我已经定义协议:

@protocol PlayerProfileSectionProReviewDelegate <NSObject>

- (void)didReceivedPlayerProfileSectionProReviewData;

@end

@interface PlayerProfileSectionProReviewModel : PlayerProfileSectionModel

@property (weak) id <PlayerProfileSectionProReviewDelegate> playerProfileSectionProReviewDelegate;

@end

在这个 class 实现中,我调用委托:

if ([self.playerProfileSectionProReviewDelegate respondsToSelector:@selector(didReceivedPlayerProfileSectionProReviewData)])
{
    [self.playerProfileSectionProReviewDelegate didReceivedPlayerProfileSectionProReviewData];
}

在视图控制器中,我添加了 PlayerProfileSectionProReviewDelegate 并覆盖了 didReceivedPlayerProfileSectionProReviewData 方法:

@interface PlayerProfileSectionProReviewViewController : PlayerProfileSectionViewController <UITableViewDelegate, UITableViewDataSource, PlayerProfileSectionProReviewDelegate>

@end

#pragma mark <PlayerProfileSectionProReviewDelegate>

- (void)didReceivedPlayerProfileSectionProReviewData
{
    [self.playerProReviewTableView reloadData];
}

为什么我的协议不响应选择器?

在您的 PlayerProfileSectionProReviewViewController class 实现中的某处,您需要设置适当的 PlayerProfileSectionProReviewModel 对象的委托,如下所示:

myModel.playerProfileSectionProReviewDelegate = self;

如果您这样做,那么当 myModel 到达您的委托调用时,您的视图控制器将收到它。

顺便说一下,您可以简化这些行:

if ([self.playerProfileSectionProReviewDelegate respondsToSelector:@selector(didReceivedPlayerProfileSectionProReviewData)])
{
    [self.playerProfileSectionProReviewDelegate didReceivedPlayerProfileSectionProReviewData];
}

有:

[self.playerProfileSectionProReviewDelegate didReceivedPlayerProfileSectionProReviewData];

此时如果委托是nil,则不会发送任何消息,您也不会收到任何运行时错误。