Question

In xcode I've noticed there is a method created automatically when a property is used.

For example, if I enter @property(nonatomic)BOOL selected; in an @interface a method gets created in the background which can be used in the @implementation looking like this:

-(void)setSelected:(BOOL)selected {}

Now I don't really know what this is called but I assume it's called setter method, now I figured I could use this for some stuff when setting the selected boolean but when I call it and it's empty; nothing happens, not even selected gets assigned a value, and when I enter:

self.selected = selected;

It runs into an endless loop and the app crashes, is there an easy way to sop that infinite loop or should I not use these kind of methods?

FIXED

I synthesized the self.selected and now it does not loop.

@synthesize selected;

-(void)setSelected:(BOOL)selected_ {
    selected = selected_;
}
Was it helpful?

Solution

You need to access the backing iVar for the selected property in the setter

-(void)setSelected:(BOOL)selected {
  if (_selected != selected) {
     _selected = selected;
  }
}

Assigning self.selected = selected will call the setter, and calling this inside the setting will result in an endless loop!

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