简体   繁体   中英

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?

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.

Obj-C operate pointers. A lot of stuff is done at runtime, not compile time and actually you can't use Obj-C class as values, only as pointers. For example, you can get any value with valueForKey: and call any method with performSelector:. Actually, you can even change methods implementation in run-time with methods from (like class_replaceMethod).

Bottom line: Obj-C is far from what you have seen in C and C++. A lot of stuff if performed at runtime what gives some flexibility as well as some pain.. It is just different. You should read Apple docs about Obj-C or maybe a book about the language (for example, Programming in Objective-C" by Stephen G. Kochan)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM