本文介绍了在Objective-C中,+ alloc如何知道要分配多少内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个声明为的类:

Let's say I have a class declared as:

@class SomeClass

@interface SomeClass: NSObject {
  NSString *myString;
  NSString *yourString;
}

@end

然后,在其他一些代码中,我说:

And later, in some other code I say:

SomeClass *myClass = [[SomeClass alloc] init];

在没有覆盖+ alloc的情况下,SomeClass如何知道要分配多少内存?大概它需要存储ivars myString和yourString,但是它使用的是从NSObject继承的+ alloc.是否有涵盖这些细节的参考资料?

How does SomeClass know how much memory to allocate given that it didn't override +alloc? Presumably it needs storage for the ivars myString and yourString, but it's using +alloc inherited from NSObject. Is there reference material that covers these details?

推荐答案

+alloc只是一个与其他方法一样的类方法. NSObject中的默认实现使用class_getInstanceSize()来获取应分配的实例大小.实例大小是根据每个类(不继承)的编译时结构大小以及每个类和所有超类的总大小的每次运行时计算的组合来确定的.这就是在64位和iPhone运行时中实现非脆弱iVar的方式.

+alloc is just a class method like any other. The default implementation in NSObject, uses class_getInstanceSize() to get the instance size that should be allocated. The instance size is determined based upon a combination of per-class (without inheritance) compile time structure size and per-runtime calculation of total size of the class and all superclasses. This is how non-fragile iVars are possible in 64 bit and the iPhone runtimes.

某些类,尤其是类集群,实际上直到调用初始化器时才进行真正的实例分配(这就是为什么在初始化器方法中执行self = [super init]重要的原因).

Some classes, class clusters in particular, don't actually do the true instance allocation until the initializer is called (which is why it is important to do self = [super init] in your initializer methods).

这篇关于在Objective-C中,+ alloc如何知道要分配多少内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 02:03