Objective c 使用<;协议名>;创建协议时

Objective c 使用<;协议名>;创建协议时,objective-c,delegates,protocols,Objective C,Delegates,Protocols,当我创建协议时,请说: @protocol EBSoundViewProtocol <NSObject> - (void)playSoundPressed; - (void)soundHintPressed; - (void)crossOutLettersHintPressed; - (void)fillInLettersHintPressed; - (void)solveSoundHintPressed; @end 或者像这样: @property (strong, nona

当我创建协议时,请说:

@protocol EBSoundViewProtocol <NSObject>

- (void)playSoundPressed;
- (void)soundHintPressed;
- (void)crossOutLettersHintPressed;
- (void)fillInLettersHintPressed;
- (void)solveSoundHintPressed;

@end
或者像这样:

@property (strong, nonatomic) id delegate;
@property (strong, nonatomic) id<EBSoundViewProtocol> delegate;
@property(强,非原子)id委托;
因为我不能真正理解差异,我没有测试,但我认为第一个很好,为什么我需要呢?

应该是:

@property (strong, nonatomic) id<EBSoundViewProtocol> delegate;
@property(强,非原子)id委托;
因为这告诉编译器委托实现协议
EBSoundViewProtocol

,它应该是:

@property (strong, nonatomic) id<EBSoundViewProtocol> delegate;
@property (strong, nonatomic) id<EBSoundViewProtocol> delegate;
@property(强,非原子)id委托;

因为这告诉编译器委托实现协议
EBSoundViewProtocol

Grady Player是正确的;括号中的位仅表示对象应符合协议。如果添加
,您将收到协议中任何必需但未实现的方法的警告

@property (strong, nonatomic) id<EBSoundViewProtocol> delegate;
声明协议时,还可以使用
@optional
关键字添加非必需的方法,如下所示:

@protocol EBSoundViewProtocol <NSObject>

- (void)playSoundPressed;
- (void)soundHintPressed;

@optional

- (void)crossOutLettersHintPressed;
- (void)fillInLettersHintPressed;
- (void)solveSoundHintPressed;

@end
两种方法都可以


哦,正如勒内所指出的,你可能应该让你的代理属性变弱,而不是变强,以避免保留循环;括号中的位仅表示对象应符合协议。如果添加
,您将收到协议中任何必需但未实现的方法的警告

声明协议时,还可以使用
@optional
关键字添加非必需的方法,如下所示:

@protocol EBSoundViewProtocol <NSObject>

- (void)playSoundPressed;
- (void)soundHintPressed;

@optional

- (void)crossOutLettersHintPressed;
- (void)fillInLettersHintPressed;
- (void)solveSoundHintPressed;

@end
两种方法都可以


哦,正如勒内所指出的,您可能应该让您的委托属性变弱,而不是变强,以避免保留循环。

但这只是一个编译器检查,对运行时没有任何影响,只是一个很好的(Duck)类型正确性机制。但它只是一个编译器检查,对运行时没有任何影响,只是一个很好的(Duck)类型的正确性机制。稍微偏离主题,但委托属性通常应该是弱引用。稍微偏离主题,但委托属性通常应该是弱引用。无论哪种方法都有效,尽管您可能希望在禁用协议标识符的情况下调用委托之前使用-respondsToSelector:。但无论哪种方法都可以,尽管您可能希望在禁用协议标识符的情况下调用委托之前使用-respondsToSelector:。