iosinitwithcoder

initwithCoder and encodewithCoder on iOS


I have tried to save the state of a UIButton by using encodeWithCoder:

- (void)encodeWithCoder:(NSCoder *)encoder
{  
  [coder encodeObject:self.button1 forKey:@"button1"];
}

My initWithCoder: looks like this:

-(void) initWithCoder:(NSCoder*)decoder
{
  self.button1 = [coder decodeObjectForKey:@"button1"];
}

With button1 I save the state of the color, orientation, angle etc. And I can restore it with initwithCoder; but when I tap the button it doesn't respond. The appearance has been restored but the IBAction is no longer called.


Solution

  • If you're manually creating/restoring your buttons then you're taking away the automatic setup that InterfaceBuilder/NIB loading does for you.

    You will need to add the target action to the button explicitly. You also have some syntax errors in your example code.

    -(void) initWithCoder:(NSCoder*)decoder
    {
      self.button1 = [coder decodeObjectForKey:@"button1"];
      [self.button1 addTarget:self action:@selector(yourIBActionMethod:) forControlEvents:UIControlEventTouchUpInside];
    }