简体   繁体   中英

initWithCoder: getting called by nib & NSCoding!

Ok, I'm having a lot of problems right now trying to get initWithCoder: to work right. I have a nib file that gets loaded, and in my app delegate, I call unarchiveWithFile: for the view controller that is associated with that nib, and now my app crashes. I can see that initWithCoder: is being called twice, presumably once from when awakeFromNib: is called, and then from when I call unarchiveWithFile: since the view controller conforms to NSCoding. But now either it crashes as soon as the view loads or when I press an IBOutlet. Any suggestions??

Edit: Here's the code for initWithCoder:

- (id)initWithCoder:(NSCoder *)coder {
    [super initWithCoder:coder];
    [[self mapView] addAnnotations:[[coder decodeObjectForKey:@"Annotations"] retain]];
    return self;
}

All I'm doing is decoding an array of annotations for a map view, but somewhere along the line this method is being called twice and then it crashes.

Don't forget to put the nil check in your init methods. Eg the method you posted would be more correct if you wrote it as:

- (id)initWithCoder:(NSCoder *)coder {
    if (self = [super initWithCoder:coder]) {
        [[self mapView] addAnnotations:[[coder decodeObjectForKey:@"Annotations"] retain]];
    } 
    return self;
}

That's not the cause of your problem, however.

Is there are good reason for you unarchiving your view controller yourself? If you're not doing anything special, you can rely on the existing mechanisms to do it. The default implementation of init for a UIViewController looks for a nib with the same name as your view controller, and if it exists, it loads the nib (via initWithNibName).

If there is data which you need to archive in and out, it may be that it shouldn't be actually part of the UIViewController. Factor it out elsewhere perhaps?

you can try

- (id)initWithCoder:(NSCoder *)coder {
     if(self == nil)
     {
          [super initWithCoder:coder];
          [[self mapView] addAnnotations:[[coder decodeObjectForKey:@"Annotations"] retain]];
     }
      return self;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM