I am trying to use delegation between two Viewcontrollers, but unfortunately my delegate doesn´t get fired. I hope somebody can help me fix the problem. I have a ViewContoller called MapBackgroundViewController and one called MapsViewController. The MapsViewController should be informed if the SegmentedControl of the MapsBackgroundViewController changes. (I actually try to implement something like the maps app on iPhone with patrial curl)
Here is part of my code:
MapBackgroundViewController.h
@protocol ChangeMapTyp <NSObject>
@required
- (void)segmentedControllChangedMapType:(MKMapType) type ;
@end
@interface MapBackgroundViewController : UIViewController{
IBOutlet UISegmentedControl *segmentedControl;
MKMapType mapType;
id < ChangeMapTyp> delegate;
}
@property IBOutlet UISegmentedControl *segmentedControl;
@property MKMapType mapType;
@property(strong)id delegate;
- (IBAction)segmentedControllChanged:(id)sender;
MapBackgroundViewController.m
@interface MapBackgroundViewController ()
@end
@implementation MapBackgroundViewController
@synthesize segmentedControl, mapType, delegate;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
[self setDelegate:self];
NSLog(@"%@",self.delegate);
}
- (IBAction)segmentedControllChanged:(id)sender {
if (segmentedControl.selectedSegmentIndex == 0) {
mapType = MKMapTypeStandard;
}else if (segmentedControl.selectedSegmentIndex == 1) {
mapType = MKMapTypeSatellite;
} else if (segmentedControl.selectedSegmentIndex == 2) {
// [self.delegate setMapType:MKMapTypeHybrid];
mapType = MKMapTypeHybrid;
}
//Is anyone listening
NSLog(@"%@",self.delegate);
if([self.delegate respondsToSelector:@selector(segmentedControllChangedMapType:)])
{
//send the delegate function with the amount entered by the user
[self.delegate segmentedControllChangedMapType:mapType];
}
[self dismissModalViewControllerAnimated:YES];
}
MapsViewController.h
#import "MapBackgroundViewController.h"
@class MapBackgroundViewController;
@interface MapsViewController : UIViewController<MKMapViewDelegate,
UISearchBarDelegate, ChangeMapTyp >{
IBOutlet MKMapView *map;
}
@property (nonatomic, retain) IBOutlet MKMapView *map;
@end
MapsViewController.m (the below method for some reason gets never called)
- (void)segmentedControllChangedMapType: (MKMapType) type{
map.mapType = type;
}
In
MapBackgroundViewController
you have set thedelegate
property toself
, so the delegate isself
- (MapBackgroundViewController
) so when you perform the checkif([self.delegate respondsToSelector:@selector(segmentedControllChangedMapType:)])
it returnsNO
, becauseself.delegate
(which isself
, which isMapBackgroundViewController
), does not implement this method. If you want yourMapsViewController
to be the delegate, in yourMapBackgroundViewController
you must have an instance ofMapsViewController
(calledmyMapsViewController
for example) and then set theself.delegate = myMapsViewController
.