简体   繁体   中英

Delegate for the iOS

I'm trying to see why the type can't be read from the protocol. I figured that the it's because the @interface is below the protocol but if someone can help me figure out the problem and explain to me why that would be great.

#import <UIKit/UIKit.h>

@protocol ARCHCounterWidgetDelegate <NSObject>

    - (UIColor *) counterWidget: (ARCHCounterWidget *) counterWidget;

@end

@interface ARCHCounterWidget : UIView

    @property (weak, nonatomic) id<ARCHCounterWidgetDelegate> delegate;

@end

You have to either forward declare the class or the protocol:

// tell the compiler, that this class exists and is declared later:
@class ARCHCounterWidget;

// use it in this protocol
@protocol ARCHCounterWidgetDelegate <NSObject>
- (UIColor *) counterWidget: (ARCHCounterWidget *) counterWidget;
@end

// finally declare it
@interface ARCHCounterWidget : UIView
@property (weak, nonatomic) id<ARCHCounterWidgetDelegate> delegate;
@end

or:

// tell the compiler, that this protocol exists and is declared later
@protocol ARCHCounterWidgetDelegate;

// now you can use it in your class interface
@interface ARCHCounterWidget : UIView
@property (weak, nonatomic) id<ARCHCounterWidgetDelegate> delegate;
@end

// and declare it here
@protocol ARCHCounterWidgetDelegate <NSObject>
- (UIColor *) counterWidget: (ARCHCounterWidget *) counterWidget;
@end

The compiler is not yet aware of the ARCHCounterWidget, and therefore cannot resolve the type in the delegate method. Simple solution is:

#import <UIKit/UIKit.h>

// Reference the protocol
@protocol ARCHCounterWidgetDelegate

// Declare your class
@interface ARCHCounterWidget : UIView

    @property (weak, nonatomic) id<ARCHCounterWidgetDelegate> delegate;

@end

// Declare the protocol
@protocol ARCHCounterWidgetDelegate <NSObject>

    - (UIColor *) counterWidget: (ARCHCounterWidget *) counterWidget;

@end

It just makes it so that the compiler knows that the protocol is defined SOMEWHERE and can be referenced

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