Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS automatic @synthesize without creating an ivar

Tags:

ios

ivar

If I have a @property which I didn't want to have backed via an ivar I simply omitted the @synthesize and had manual getters which returned a calculated value.

However, now since Xcode 4.4 if I don't specify @synthesize do compiler will automatically generate it. Does that mean it will also generate an ivar even do I don't need/use it?

I could eventually force to not auto-synthesize by using dynamic. However that would be wrong, since @dynamic is supposed to be used for turning off warnings if getter and setter are implemented somewhere else or during runtime.

like image 735
znq Avatar asked Oct 17 '12 11:10

znq


2 Answers

In my working with this, I've noticed the following behavior.

  1. If you have a readwrite property, don't have a @synthesize, have a getter and don't have a setter, then it will generate the iVar.
  2. If you have a readwrite property, don't have a @synthesize, don't have a getter, and have a setter, then it will generate the iVar.
  3. If you have a readwrite property, don't have a @synthesize and have both a getter and a setter, then it will not generate the iVar.
  4. If you have a readonly property, don't have a @synthesize and don't have a getter, then it will generate the iVar.
  5. If you have a readonly property, don't have a @synthesize and have a getter, then it will not generate the iVar.

From this, I think the general rule is that if you don't have a @synthesize, and have all the methods needed to fully implement the property, then it's assumed to be dynamic and doesn't generate the iVar.

At any rate, if you want to ensure that an iVar is not generated then declare it as @dynamic.


Clarification on @dynamic

From Declared Properties in The Objective-C Programming Language:

You use the @dynamic keyword to tell the compiler that you will fulfill the API contract implied by a property either by providing method implementations directly or at runtime using other mechanisms such as dynamic loading of code or dynamic method resolution.

To me this reads like it OK to mark a property as @dynamic even when you are directly implementing the getter and setter.

like image 64
Jeffery Thomas Avatar answered Oct 21 '22 06:10

Jeffery Thomas


If you mark the property as readonly and implement the getter yourself, it seems that iVar will not be created.

Interface declaration:

@property (nonatomic, readonly) BOOL myBoolProp;

Impementation:

- (BOOL)myBoolProp {
    return true;
}

Trying this:

- (void)viewDidLoad {
    [super viewDidLoad];
    _myBoolProp = true;
}

will generate an error: Use of undeclared identifier '_myBoolProp'

Removing the custom getter method also removes the error, appearing to demonstrate that the iVar has now been generated.

like image 35
Ian L Avatar answered Oct 21 '22 07:10

Ian L