Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override @property setter and infinite loop

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.

like image 981
Marcin Avatar asked Jun 19 '11 22:06

Marcin


2 Answers

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?

like image 120
Sherm Pendley Avatar answered Nov 18 '22 01:11

Sherm Pendley


With XCode 4.5+ and LLVM 4.1 there is no need to @synthesize, you will get a _prop1 to refer to.

- (void) setProp1:(id)aProp
{
    _prop1 = aProp;
}

Will work just fine.

like image 24
bollhav Avatar answered Nov 17 '22 23:11

bollhav