Override @property setter and infinite loop

Marcin picture Marcin · Jun 20, 2011 · Viewed 28.2k times · Source

There is Class A with:

@interface ClassA : NSObject {
}
@property (nonatomic, assign) id prop1;
@end

@implementation
@synthesize prop1;
@end

then I have subclass

@interface ClassB : ClassA {
}
@end

@implementation

- (id)init {
    self = [super init];
    if (self) {
    }
    return self;
}

//This is infinite loop
- (void) setProp1:(id)aProp
{
    self.prop1 = aProp;
}
@end

and this is infinite loop because setProp1 from ClassB calls [ClassB setProp1:val] from within ClassB.

I've already tried call [super setProp1] but this

How to overwrite @property and assign value inside overwritten setter ? And let's assume I can't modify ClassA.

Answer

Sherm Pendley picture Sherm Pendley · Jun 20, 2011

Just assign to the instance variable directly, without using dot syntax to call the setter:

- (void) setProp1:(id)aProp
{
    self->prop1 = aProp;
}

That kind of begs the question though. All this accessor does is exactly what the parent would have done - so what's the point of overriding the parent at all?