【问题标题】:Defining and using protocols in objective-c在 Objective-C 中定义和使用协议
【发布时间】:2009-06-10 14:18:30
【问题描述】:

我正在尝试扩展 NSImageView,以便我可以将拖放职责委托给控制器。对于编译器现在显示有关向具有类型 id 的对象发送消息的警告的一个问题,这一切都很好。为了解决这个问题,我假设我只需在 ivar 的类型后面加上协议名称即可。但是,这会以找不到协议定义的消息而惨遭失败。

#import <Cocoa/Cocoa.h>


@interface DragDropImageView : NSImageView {
    id <DragDropImageViewDelegate> _delegate;
}

@property (readwrite, retain) id <DragDropImageViewDelegate> delegate;

@end

@protocol DragDropImageViewDelegate

@optional

- (NSDragOperation)dragDropImageView:(DragDropImageView *)ddiv validateDrop:(id     <NSDraggingInfo>)info;
- (BOOL)dragDropImageView:(DragDropImageView *)ddiv acceptDrop:(id <NSDraggingInfo>)info;
- (void)concludeDragOperation:(id <NSDraggingInfo>)sender;  

@end

我可能会出错的任何指针?我敢肯定它一定很简单,但我对 obj-c 很陌生。

【问题讨论】:

  • +1 提出好问题。
  • 关键字是:前向声明

标签: objective-c macos cocoa-touch cocoa nsdragginginfo


【解决方案1】:

你在正确的轨道上,但你被 C 编译器挂断了,这有点过时了。编译器令人窒息,因为在您使用它时协议的定义不可用。必须先定义 @protocol DragDropImageViewDelegate,然后才能使用 id&lt; DragDropImageViewDelegate&gt; 作为类型。您可以在使用之前移动@protocol 定义(即在您的@interface 之前),或者添加一个

@protocol DragDropImageViewDelegate;

在@interface(前向声明)之前并将@protocol 声明保留在原处。

【讨论】:

  • 美丽。谢谢你。实际上,我不得不进行前向声明,因为将协议声明移到 @implementation 之上引入了协议的问题,现在它在定义之前引用了 DragDropImageView。感谢您的帮助!
  • 是的,当然会。一般来说,前向声明是解决这种类型的循环依赖的方法。
  • +1 表示不错的答案。我有一点疑问,当我们写 \@protocol DragDropImageViewDelegate;在\@interface之前,那么编译器做了什么?
【解决方案2】:

作为一般规则,我首先定义协议,然后是

@class DragDropImageView;

但你可以反过来做:

@protocol DragDropImageViewDelegate;

在我看来,协议是声明的重要组成部分,而且往往很短,所以我更喜欢它先出现而不是丢失在头文件的底部,但这只是个人喜好问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-15
    • 2012-06-10
    • 2011-06-15
    • 1970-01-01
    • 2011-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多