子类化内存分配问题
我有一个关于使用对象子类化类的基本问题:
@interface Myclass : NSObject{
UIImage *image; NSString *字符串; 粒子系统*系统; 对象*obj; 对象2 *obj2; ?
如果我对这个 MyClass 类进行子类化,并且只初始化超类标头中定义的几个对象,那么所有其他未分配的定义在内存方面会发生什么 我问的原因是,我有一个包含很多定义的类,为了简单起见,我一直在对它进行子类化,但我的子类只需要这些定义的一小部分。
是否值得只子类化 NSObject 并重新定义所需的变量而不是子类化 MyObject ?
谢谢, 奥利弗.
I have a basic question about subclassing a class with objects:
@interface Myclass : NSObject{
UIImage *image;
NSString *string;
ParticleSystem *system;
Object *obj;
Object2 *obj2;
}
If I subclass this MyClass class, and I initialise only a few of these objects defined in the superclasses header, what happens to all the other unallocated definitions in terms of memory?
The reason I ask, I have a class with many, many definitions and i've been subclassing it for simplicity sake, but my subclass only needs a fraction of these definitions.
Is it worth just subclassing NSObject and redefining the needed variables rather than subclassing MyObject?
Thanks,
Oliver.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它们占用空间,但每个变量仅占用一个指针的空间(在 iPhone 上为 4 个字节)。
将它们分成单独的类的更好原因是,听起来您没有非常清晰的职责划分。类应该由数据的某种逻辑分组以及对该数据的操作组成。与班级角色无关的事情可能属于其他地方。
They take up space, but only a pointer's worth (4 bytes on the iPhone) per variable.
The better reason for separating these out into separate classes is that it sounds like you don't have a very clean division of responsibilities. A class should be composed of some logical grouping of data and operations on that data. Things not having to do with the class's role probably belong elsewhere.
每个变量都是一个指针,因此它们占用指向内存地址所需的存储空间。 (iPhone 上为 4 字节)
iPhone 操作系统是 64 位还是 32 位?< /a>
如果每个子类只需要一个小子集,则只包含基类中的子集(而不是在每个类中复制和重新定义)。如果其中一些子类需要全套,那么您还可以拥有类层次结构(分层子类)。不看到具体设计就不可能知道。
Each of those variables is a pointer so they are taking up the storage required to point to a memory address. (4 bytes on iPhone)
Is iPhone OS 64 bit or 32 bit?
If each of the sub classes only needs a small subset, then only include those in the base class (rather than copying and redefining in those in every class). If some of those subclasses require the full set, then you can also have a class hierarchy (layered sub-classes). It's impossible to know without seeing the concrete design.
如果类定义中只有指针(例如,
SomeClassName* somePointerName;
),则每个指针在每个对象中占用一个指针位置(在 iPhone 上为 4 个字节)。虽然偶尔做你正在做的事情很方便,但你错过了面向对象编程的许多好处——你基本上只是在编写蹩脚的 C 代码时使用 Objective-C 的存储管理。
If you just have pointers in the class definition (eg,
SomeClassName* somePointerName;
) then each pointer takes up one pointer location in each of your objects (4 bytes on iPhone).Though it's occasionally convenient to do what you're doing, you're missing out on many of the benefits of object-oriented programming -- you're basically just making use of Objective-C's storage management while coding cruddy C.