为什么从 NSObject 继承的对象的大小是 16bytes

发布于 2024-12-14 19:40:45 字数 232 浏览 1 评论 0原文

我有一个继承自 NSObject 的新对象,

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

它返回 16,即 Car 对象的大小,

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

请帮我说清楚,谢谢

I have a new object inherited from NSObject

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

This returns 16, the size of a Car object

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

plz help me to make it clear, thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

我喜欢麦丽素 2024-12-21 19:40:45

您不能使用 sizeof() 来确定 Objective-C 对象的大小。您可以使用class_getInstanceSize()来代替。

但是,由于很多很多原因,类实例的大小完全没有用处。

你想做什么?

You can't use sizeof() to determine the size of an Objective-C object. You can use class_getInstanceSize() instead.

However, the size of an instance of a class is quite thoroughly useless for many, many, reasons.

What are you trying to do?

薄荷梦 2024-12-21 19:40:45

sizeof 在这种情况下像 C 一样工作。

正如 bbum 所说,你不应该在 NSObject 类型上使用 sizeof (而是指向 NSObject< /code> 没问题)。 Clang 禁止请求 sizeof 和对象。如果您需要对象的大小,则 objc 运行时应该是您的参考,因为 objc 对象的实际大小不是静态(编译时)值,而是在运行时确定的。

给定这些类型:

@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 位上,我们得到:

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

在 32 位上,我们得到:

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

有一个小例子向您展示了大小增长的原因。有关更多详细信息,此处是维基百科页面。

sizeof in this case works like C.

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.

Given these types:

@interface A : NSObject
@end

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

And these messages:

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

On 64 bit, we get:

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

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.

夏末染殇 2024-12-21 19:40:45

这是分配给存储 NSObject 类对象的字节数。

你为什么不喜欢它?

This is the number of bytes that was allocated to store object of class NSObject.

Why do not you like it?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文