LondonGuy LondonGuy - 3 months ago 9x
iOS Question

What does aDecoder in the initWithCoder method do in cocoa-touch?

Following my previous post about

designated initializer
I have another question about the argument
passed into the protocol method.

Here is the code in question:

@implementation WhereamiViewController

- (id)initWithCoder:(NSCoder *)aDecoder //we're overiding the superclasses (UIViewController) inititalizer
self = [super initWithCoder:aDecoder];

if (self){
//create location manager object
locationManager = [[CLLocationManager alloc] init];

//there will be a warning from this line of code
[locationManager setDelegate:self];

//and we want it to be as accurate as possible
//regardless of how much time/power it takes
[locationManager setDesiredAccuracy:kCLLocationAccuracyBest];

//tell our manager to start looking for its location immediately
[locationManager startUpdatingLocation];

return self;

I was curious about aDecoder so renamed it to see if my code would still work and it did. What I want to know is what exactly is being passed into initWithCoder as an argument? It seems like nothing is in my code. Is the argument just part of the method and has to be shown even if nothings being passed into it? Other times I have created designated initializers I've done it like this:

self = [super init]

init is NSObjects designated initializer right?

This is the only part of the code I don't understand. I see I'm calling my superclasses initializer and then implementing it with additional custom code / making it selfs (whereamiviewcontroller) value.

I did set a marker and look in the logs to see if anything would catch my eye but had no luck with that.

Thanks in advance



You can see the -initWithCoder: method in action when you try to initialise your view controller instance from nib or storyboard. In this case Cocoa Touch will decode the controller elements from the xml using UINibDecoder instance by -initWithCoder: initialiser.