Filip Filip - 4 months ago 30
Objective-C Question

Accessing Delegate in Subclass

I searched around for this but couldn't find any answer that works.. How do I successfully access the delegate methods from a subclass?

Like so:

#import <MapKit/MapKit.h>

@protocol customMapViewDelegate <MKMapViewDelegate>
//
@end

@interface customSubClass : MKMapView <MKMapViewDelegate>
//
@end


Basically, I'd like to access the MkMapView delegates in my subclass and not in the file that I'm implementing
customSubclass
in.

Answer

Add this to your MKMapView.h file :

@protocol MKMapViewDelegate <NSObject>
@required
// Put your required delegate methods here
-(void)myFirstRequiredMethod;

@optional
// Pute your optional delegate methods here

@end

And then you can use the delegate methods in your customSubClass.m file :

@interface customSubClass : MKMapView <MKMapViewDelegate>

-(void)myFirstRequiredMethod
{
    NSLog(@"Hello");
}

@end

c.f. this link for more information : http://www.idev101.com/code/Objective-C/delegate.html

EDIT ( after comment from OP ) Sometimes, you don't want to set self as the delegate of an object. You can perfectly set an other object as the delegate.

    @interface customDelegate : MyCustomDelegateClass <MKMapViewDelegate>

    -(void)myDelegateMethod
    {
        NSLog("hello")
    }

    @end

Then, your customSubClass should have a property of type customDelegate

customSubClass.h :

@interface customSubClass : MKMapView <MKMapViewDelegate>
{
}

@property (nonatomic, weak) MyCustomDelegateClass  *myCustomDelegate;
@property (nonatomic, strong) MKMapView  *myMKMapView;


@end

customSubClass.m :

@implementation MainViewController


- (void)viewDidLoad {

    [super viewDidLoad];
    self.myMKMapView.delegate = self.myCustomDelegate
}
}