Search code examples
objective-caccessordeclared-property

Does setting a property on a property call the first property's setter?


If a class has a custom setter for a property:

@interface OuterClass : NSObject
@property InnerClass *obj;
-(void)setObj:(InnerClass *)obj;

and InnerClass itself has a property:

@property NSString *text;

and I then do: obj.text = @"Hello"; will that activate the OuterClass object's setObj: method?


Solution

  • Sorry I misunderstood the context of your original question.

    Calling someObject.obj.text = @"Hello" will not call -setObj on the outer class.

    @properties generate simple setters and getters and do not observe changes made to members of ivars.

    It will however call -obj on someObject.

    Think of it like this. Given someObject.obj.text =, the someObject.obj section uses the getter of someObject to return obj. The obj.text = part then sends -setText to the result of the obj getter.

    BEFORE EDIT:

    Yes, an @property automatically generates a setter and getter for the ivar.

    Setting obj.text = @"hello" calls the -setText: method.

    and accessing the property x = obj.text calls the -text method.

    Make sure if you override a setter or getter that the method matches the property exactly.