自动@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@的的一一一一一一一文一书@@@@@@@@@@@@@@@@@@ [英] How do automatic @synthesized ivars affect the *real* sizeof(MyClass)?

查看:85
本文介绍了自动@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@的的一一一一一一一文一书@@@@@@@@@@@@@@@@@@的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我包括这样的一些自动属性:

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;

但是我不为它们声明任何iVar,我可以在.m文件中@合成它们,如下所示:

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;

,这没有问题,编译器会自动添加iVars-sizeof(MyClass)表明我的类(如您预期的那样)比没有声明和合成这些属性的情况大16个字节.但是,如果我不合成它们,而是像这样实现它们:

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;
}

然后我的课又回到了原来的大小.这是根据MyClass .m文件中sizeof的大小确定的-因此,编译器在此阶段知道变量是已合成还是已实现.

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.

但是,其他类并不仅仅从头文件知道这一点,无论是否合成,sizeof(MyClass)都会显示大小而没有其他(自动)iVar.这似乎完全让我感到困惑,sizeof可以返回不同的值.如果不能确定类的大小,那么在进行子类化时以及在子类的公共iVar上使用dereference + offset(->)运算符时,编译器如何正确执行?

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.

sizeof运算符的使用对Obj-C对象几乎没有用.我相信运行时不会使用它来操纵事物.

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.

这篇关于自动@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@的的一一一一一一一文一书@@@@@@@@@@@@@@@@@@的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆