简体   繁体   中英

Declaring delegate protocol in the same file

I have following header:

@protocol AttachmentsViewDelegate <NSObject>

@required
- (void)spaceRequestedWithSize:(CGSize)size sender:(AttachmentsView*)sender;

@end

@interface AttachmentsView : UIView

@property id<AttachmentsViewDelegate> delegate;
@property NSArray *attachments;

- (void)takePicture;
- (void)deletePictures;

@end

Doesn't work because inside @protocol I reference to AttachmentsView and it's not declared yet.

If I move @protocol below @interface - I have another problem, because delegate property doesn't know about @protocol.

I know I can use id, UIView for types, but to keep it "strongly typed", what can I do? I really prefer not to break it down into 2 files. Any other options/suggestions?

Use @class to forward-declare AttachmentsView like so:

@class AttachmentsView;

@protocol AttachmentsViewDelegate <NSObject>

// Protocol method declarations...

@end

Alternatively, use @protocol to forward-declare the protocol:

@protocol AttachementsViewDelegate

@interface AttachmentsView : UIView

// Ivar, method, and property declarations...

@property id<AttachmentsViewDelegate> delegate;

@end

just write:

@class AttachmentsView;

on top of the file.

In case you wish to declare the class first, and then the protocol, write first:

@protocol AttachmentsViewDelegate;

on top of the file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM