Automatic synthesize creates an instance variable with a underscore prefix, so a property called test
generates a backing instance variable of _test
. So you have two instance variables; test
, which isn't connected to the property, and _test
. If you write to the instance variable test
, it will not be reflected in _test
or the property's value.
But more to the point, declaring the backing instance variable yourself is pointless. It's just an extra code and unnecessary redundancy. The @property
line already contains type, name, whether it's read/write or read-only and a storage qualifier. Just skip declaring the backing instance variable yourself and use the one the compiler generates for you.
In Engine.h:
@interface Engine : NSObject
@property (readonly, assign) NSInteger test;
- (void)doSomething;
@end
In Engine.m:
@implementation Engine
- (void)doSomething {
_test++; // _test is created automatically by the compiler
}
@end
In other.m:
Engine *engine = [[Engine alloc] init];
NSLog(@"%d", engine.test); // 0
[engine doSomething];
NSLog(@"%d", engine.test); // 1
This all just works. Don't add to it.