Search code examples
iosiphoneobjective-cios5getter-setter

Custom setter not getting called in UIView


I am using a custom setter for a bool property as I need to do some extra work when this value changes. Here is my implementation:

MyView.h

@interface MyView : UIView 

@property (nonatomic) BOOL isSelected;

@end

MyView.m

@implementation MyView

@synthesize isSelected;

-(void)setIsSelected:(BOOL)_isSelected
{
    self.isSelected = _isSelected;

    //Custom code that changes UI based on bool state  


}

@end

However the setter is not getting called! Can someone tell me why?


Solution

  • Two ways to set your property and your setter method get called.

    1、Dot Syntax : self.isSelected = YES ; 2、call it directly. [set setIsSelected:YES] ;

    @interface MyView : UIView 
    @property (nonatomic) BOOL isSelected;
    @end
    
    @implementation MyView
    @synthesize isSelected;
    -(void)setIsSelected:(BOOL)_isSelected
    {
        isSelected = _isSelected;
        //Custom code that changes UI based on bool state  
    }
    @end
    

    Your app crash because you call self.isSelected = _isSelected in your setter method, it will call your setter method recursively and endlessly until the stack over flow !