0

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:

  • In example 1 we declare @class before protocol, is it really necessary? or just best practice. Second example works fine without this declaration.
  • In example 1 we use @synthesize delegate as I understand it makes getters/setters for the property but do we really need it? Second example works without this.

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

Thanks!

Community
  • 1
  • 1
Kosmetika
  • 20,774
  • 37
  • 108
  • 172
  • 1
    It's a good idea to pass the source instance to the delegate. Take a look at Apples delegate implementation (like `UITableViewDelegate`) for better examples of well formed protocols. – Wain May 18 '14 at 15:42
  • Don't forget to check if the delegate responds to the selector before calling myClassDelegateMethod: since myClassDelegateMethod: is specified as @optional. – Jonathan May 18 '14 at 16:39

2 Answers2

3

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.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
1

@class tells the compiler that a class exists before reaching its @interface. It's useful when two class/protocol headers would have to #import each other only. It's likely to be the case once you create your protocol.

@synthesize used to be necessary to create getters and setters, but now we also have so-called automatic properties. When you don't use @synthesize, the compiler will create an instance variable to hold the property value and will generate getters and setters anyway. @synthesize gives you slightly more control over the process but isn't necessary anymore.

zneak
  • 134,922
  • 42
  • 253
  • 328