在objective-c中定义和使用协议

Tri*_*cky 22 macos cocoa cocoa-touch objective-c nsdragginginfo

我正在尝试扩展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
Run Code Online (Sandbox Code Playgroud)

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

Bar*_*ark 31

你是在正确的轨道上,但是你被C编译器挂了,这有点过时了.编译器很窒息,因为在使用协议时定义不可用.@protocol DragDropImageViewDelegate必须先定义才能id< DragDropImageViewDelegate>用作类型.您可以在使用之前(即在@interface之前)移动@protocol定义,或者添加一个

@protocol DragDropImageViewDelegate;
Run Code Online (Sandbox Code Playgroud)

在@interface(前向声明)之前,将@protocol声明保留在原来的位置.


Pet*_*wis 10

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

@class DragDropImageView;
Run Code Online (Sandbox Code Playgroud)

但你可以做相反的事情,并在前面:

@protocol DragDropImageViewDelegate;
Run Code Online (Sandbox Code Playgroud)

在我看来,协议是声明的一个重要部分,并且往往很短,所以我更喜欢它先行而不是丢失在头文件的底部,但这是一个品味问题.