本文介绍了为什么从NSObject继承的对象的大小为16bytes的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个继承自NSObject

Car *myCar = [[Car alloc] init];

这将返回16,即Car对象的大小

This returns 16, the size of a Car object

printf("myCar object: %d\n", sizeof(*myCar));

请帮助我说清楚,谢谢

推荐答案

sizeof在这种情况下的工作方式类似于C.

sizeof in this case works like C.

正如bbum所说,您不应在NSObject类型上使用sizeof(但是指向NSObject的指针是可以的). Clang禁止请求sizeof和对象.如果需要对象的大小,则应该使用objc运行时作为参考,因为objc对象的实际大小不是静态(编译时)值,而是在运行时确定的.

As bbum said, you should not use sizeof on NSObject types (but pointers to NSObjects are ok). Clang forbids requesting the sizeof and object. The objc runtime should be your reference if you need an object's size because the actual size of an objc object is not a static (compile-time) value, it is determined at runtime.

给出以下类型:

@interface A : NSObject
@end

@interface B : A
{
    uint64_t ivar;
}
@end

这些消息:

printf("Class size is %lu\n", sizeof(Class)); // << for NSObject.isa
printf("NSObject size is %lu\n", sizeof(NSObject));
printf("A size is %lu\n", sizeof(A));
printf("B size is %lu\n", sizeof(B));

在64位上,我们得到:

On 64 bit, we get:

Class size is 8
NSObject size is 8
A size is 8
B size is 16

在32位上,我们得到:

And on 32 bit, we get:

Class size is 4
NSObject size is 4
A size is 4
B size is 12

有一个小例子,向您展示为什么尺寸会增加.有关更多详细信息,请此处是维基百科页面.

There's a little example which shows you why sizes grow. For more detail, here is the wikipedia page.

这篇关于为什么从NSObject继承的对象的大小为16bytes的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 17:48