Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
531 views
in Technique[技术] by (71.8m points)

objective c - How do automatic @synthesized ivars affect the *real* sizeof(MyClass)?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Read this excellent post non-fragile ivars by the always helpful hamster. Also read this post with love.

The use of the sizeof operator is pretty useless to an Obj-C object. The runtime does not use it to manipulate things, I believe.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...