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 re
Yes - iVars are still generated by clang
(not Xcode, as it is the IDE, clang is the complier that really matters).
If you really don't want iVars, and don't want an implementation, there is the somewhat archaic @dynamic
keyword that will do what you want, or you can specify the property in a protocol, which doesn't make it auto-synthesized:
// .h
@property (nonatomic, retain) NSObject *someProp;
//.m
@dynamic someProp; // no iVars generated
// other solution
@protocol MyObjectProtcol<NSObject>
@property (nonatomic, retain) NSObject *someProp;
@end
// now, when you implement the MyObjectProtocol protocol, the property won't auto-synthesize.
In my working with this, I've noticed the following behavior.
@synthesize
, have a getter and don't have a setter, then it will generate the iVar.@synthesize
, don't have a getter, and have a setter, then it will generate the iVar. @synthesize
and have both a getter and a setter, then it will not generate the iVar.@synthesize
and don't have a getter, then it will generate the iVar.@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.
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.