在UIView中没有调用自定义setter

时间:2014-01-24 06:54:37

标签: ios iphone objective-c ios5 getter-setter

我正在为bool属性使用自定义setter,因为当这个值发生变化时我需要做一些额外的工作。这是我的实施:

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

然而,安装者没有被召唤!有人可以告诉我为什么吗?

5 个答案:

答案 0 :(得分:4)

设置属性的两种方法和setter方法被调用。

1,Dot Syntax:self.isSelected = YES; 2,直接调用它。 [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

您的应用程序崩溃是因为您在setter方法中调用了self.isSelected = _isSelected,它会递归地无休止地调用您的setter方法,直到堆栈溢出!

答案 1 :(得分:1)

e.g。在viewDidLoad中设置值self.isSelected=YES;,或者您要设置此值的位置。

您的setter方法应如下所示:

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

    //Custom code that changes UI based on bool state


}

如果您在setter中使用该代码:self.isSelected = _isSelected;

,则这是“setter cycle”

答案 2 :(得分:0)

尝试将-(void)setIsSelected:方法的参数_isSelected更改为其他变量selected,并使用它在方法中将属性指定为_isSelected = selected;

答案 3 :(得分:0)

试试这个,


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

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


myView.m文件中的


    @implementation customView
    @synthesize isSelected = _isSelected;


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


答案 4 :(得分:-1)

在某些情况下,当您的对象为nil时,将使您感觉未调用setter和getter。希望您能解决问题。