开发者

Objective C: When do we need to Create a new Delegate Protocol?

开发者 https://www.devze.com 2023-02-25 11:02 出处:网络
I was going through some code examples and came across this application which which has the following classes

I was going through some code examples and came across this application which which has the following classes

1) FaceView Class - Draws a face and a customizable smile 2) HappinessViewContoller Class - sets the smile in the face drawn based on input of a slider in the interface.

The program actually implements a delegate protocol in the FaceView.h class as seen below

#import <UIKit/UIKit.h>

@class FaceView;

@protocol FaceViewDelegate
- (float)smileForFaceView:(FaceView *)requestor;  // -1.0 (frown) to 1.0 (smile)
@end

@interface FaceView : UIView {
    id <FaceViewDelegate> delegate;
}

@property (assign) id <FaceViewDelegate> delegate;

@end

and the HappinessViewController declares that it is using the FaceViewDelegate

#import <UIKit/UIKit.h>
#import "FaceView.h"

@interface HappinessViewController : UIViewController <FaceViewDelegate>
{
    int happiness; // 0 to 100
    UISlider *slider;
    FaceView *faceView;
}

@property int happiness;

@property (retain) IBOutlet UISlider *slider;
@property (retain) IBOutlet FaceView *faceView;

- (IBAction)happinessChanged:(UISlider *)sender;

@end

I am a little confused on why a delegate protocol is required in this scenario. Can I just set the method "- (float)smileForFaceView:(Fac开发者_JAVA百科eView *)requestor;" directly in the HappinessViewController without declaring a delegate to the faceView?

Thanks!

Zhen Hoe


It is never required to create a protocol for delegates, but it makes it easier to ensure compatibility if there are methods which the delegate is required to implement. In this case, when the delegate is set, the FaceView object could use [newDelegate conformsToProtocol:@protocol(FaceViewDelegate)] to make sure the delegate implements any required methods. If they decide to add more required methods, they won't have to change their code because the delegate has to implement all required methods to conform.

If you don't have any required methods, then this isn't as beneficial since you can't use it for type checking. If you are writing library code, however, you should still use it, because you can put all of your possible delegate methods in there and use it as a reference.

0

精彩评论

暂无评论...
验证码 换一张
取 消