If I include some automatic properties like this:
@property (nonatomic, readonly) NSInteger test1;
@property (nonatomic, readonly) NSInteger test2;
@property (nonatomic, readonly) NSInteger test3;
@property (nonatomic, readonly) NSInteger test4;
But I DON’T declare any iVars for them, I can @synthesize them in the .m file like this:
@synthesize test1;
@synthesize test2;
@synthesize test3;
@synthesize test4;
and this works no problem, the compiler automatically adds the iVars – a sizeof(MyClass) shows that my class is (as you might expect) 16 bytes larger than without these properties declared and synthesized. However, if I don’t synthesize them and I implement them like this:
- (NSInteger)test1
{
return 0;
}
- (NSInteger)test2
{
return 0;
}
- (NSInteger)test3
{
return 0;
}
- (NSInteger)test4
{
return 0;
}
then my class is back to its original size. This is determined from a sizeof WITHIN the .m file for MyClass – so the compiler knows at this stage whether the variables were synthesized or implemented.
However, other classes do not know this just from the header file, sizeof(MyClass) shows the size WITHOUT the additional (automatic) iVars regardless of whether they are synthesized or not. This seems totally messed up to me, that sizeof can return a different value. How can the compiler behave correctly when subclassing and when using the dereference+offset (->) operator on public iVars of a subclass if it can’t be sure of the class size?
Read this excellent post non-fragile ivars by the always helpful hamster. Also read this post with love.
The use of the
sizeofoperator is pretty useless to an Obj-C object. The runtime does not use it to manipulate things, I believe.