custom setter method for delegate gets called infi

2019-09-05 17:25发布

问题:

This question already has an answer here:

  • objective C underscore property vs self 4 answers

In my VC I have declared a custom delegate property:

@interface VC2 : BaseVC
@property (nonatomic,weak) id<VC2Delegate> delegate;
@end

and from VC1, I'm setting this delegate:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if ([[segue identifier] isEqualToString: @"VC2"]) {
        self.VC2 = [segue destinationViewController];
        [self.VC2 setDelegate:self];
    }
  }

and in my VC2, I have written a setter method for the delegate:

-(void)setDelegate:(id)del{
    self.delegate=del;
}

The issue, after the pprepareForSegue method call in VC1, the setter method for delegate in VC2 gets called so many times and my apps get crashed. I'm not sure what could be the reason.

Here is the satcktrace:

I don't have any implementation my BaseVC. It's just a plain VC.

回答1:

here is your problem self.delegate is actually a setter, that is why you have cycling. You should use _delegate = del inside of your setter.



回答2:

When you're accessing your property with self.delegate, you're actually calling the getter. Try setting it to the instance variable as such:

-(void)setDelegate:(id)del{
    _delegate=del;
}


回答3:

You not required setter method because you can directly set delegate like,

 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if ([[segue identifier] isEqualToString: @"VC2"]) {
    self.VC2 = [segue destinationViewController];
    self.VC2.delegate = self;
}
 }

You just need to declare delegate property in .h file of VC2.

You can take property in VC2.h like,

   @property ViewController *delagate;

Viewconroller is you VC from wich you are calling prepareForSegue and setting delegate