开发者

Subclassing memory allocations question

开发者 https://www.devze.com 2023-04-05 20:09 出处:网络
I have a bas开发者_JS百科ic question about subclassing a class with objects: @interface Myclass : NSObject{

I have a bas开发者_JS百科ic 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.


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号