iosobjective-cclassdelegatessynthesize

objective-c - What is a proper way to declare delegates?


I'm new to objective-c and iOS development and in my class I'm declaring delegate protocol.

I found several examples of doing it and they all look very similar but have some differentiations that I want to make clear for myself and understand.

Example 1:

(links - https://stackoverflow.com/a/12660523/2117550 and https://github.com/alexfish/delegate-example/blob/master/DelegateExample/CustomClass.h)

MyClass.h

#import <BlaClass/BlaClass.h>

@class MyClass; // removed in example 2
@protocol MyClassDelegate <NSObject>
@optional
- (void) myClassDelegateMethod:(BOOL)value;
@end

@interface MyClass : NSObject
@property (nonatomic, weak) id <MyClassDelegate> delegate;
@end

MyClass.m

#import "MyClass.h"

@implementation MyClass 
@synthesize delegate; // removed in example 2

- (void) myMethodToDoStuff {
  [self.delegate myClassDelegateMethod:YES]; 
}

@end

Example 2: (links - http://www.tutorialspoint.com/ios/ios_delegates.htm)

Actually is the same except these two differences..

Things that differ them:

Both examples work fine I just want to remove the confusion rising in me.

Thanks!


Solution

  • The use of @class MyClass is required if the protocol methods have a reference to the class. It is common for protocol methods to provide a parameter to the class. You are not doing that in your example so it isn't needed.

    The use of @synthesize hasn't been needed for a while. Don't use it unless you have a specific reason to use it.