Reputation:
I am new to iOS programming. I have created ViewController with MKMapView element, and I wanted to set delegate [mapView setDelegate:self]
First I done it in method initWithNibName:bundle: like:
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
[[self map] setDelegate:self]];
UITabBarItem *item = [[UITabBarItem alloc] init];
[item setTitle:@"Map"];
[self setTabBarItem:item];
}
return self;
}
In this case MKMapView did not send me any messages, but when I placed setting delegate message to viewDidLoad
method, it worked fine.
Could someone explain me why it was not working when setting delegate message
was in initWithNibName:bundle
?
Upvotes: 0
Views: 2113
Reputation: 5775
This line is your problem:
[self map]
In initWithNibName
the map is not yet initialized and it returns nil.
In viewDidLoad
the map is already initialized.
Upvotes: 0
Reputation: 2223
Views do not get loaded in initWithNibName
, it just initializes your viewcontroller class and load the xib file which contains your view details.
When viewcontroller calls viewDidLoad
, you will have all your view objects allocated and initialized.
In your case, when you setDelegate
in initWithNibname
, you are calling it on a nil value, so nothing get set, but in viewDidLoad
mapView is allocated and initialized, so it works fine.
For a deeper insight refer:
Beautiful explanation here: What is the process of a UIViewController birth (which method follows which)?
Looking to understand the iOS UIViewController lifecycle
http://thejoeconwayblog.wordpress.com/2012/10/04/view-controller-lifecycle-in-ios-6/
Upvotes: 3