Question

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?

Was it helpful?

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 !

OTHER TIPS

e.g. in viewDidLoad set value self.isSelected=YES;, or where you want to set this value.

Your setter method should looks like:

-(void)setIsSelected:(BOOL)seleted
{
    _isSelected = seleted;

    //Custom code that changes UI based on bool state


}

This is "setter cycle" if you in setter use that code: self.isSelected = _isSelected;

Try this,


   //in myView.h
   @interface customView : UIView
  {

  }
  @property(nonatomic)BOOL *isSelected;
  @end


in myView.m file


    @implementation customView
    @synthesize isSelected = _isSelected;


    - (void)setIsSelected:(BOOL *)inSelected //inSelected is the in coming value for bool
    {
       _isSelected = inSelected;
       NSLog(@"setter is called");
    }


Try changing the -(void)setIsSelected: method's argument _isSelected to some other variable say selected and use it to assign the property as _isSelected = selected; in the method.

In some cases, when your object is nil it will give you the sense that setter and getter are not called. Hopefully you solve the problem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top