结构或类 [英] struct or class

查看:148
本文介绍了结构或类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个iPhone 3.1.3应用程序。



我有一个类 Object2D 与字段和方法;其表示形状。 Object2D 有一个代表其大小的字段,另一个代表其类型的字段。



Pattern ,这是一组形状。在 Pattern 我要有一个形状数组。从这些形状我只需要他们的大小,他们的类型和它们的位置在模式,我不需要任何方法。



我想知道最好有一个代表形状的新结构,而不是使用 Object2D 类。



我问这是因为我想内存性能。我不知道,但是struct比类更小,也许最好使用它们而不是类。



你觉得怎么样?

解决方案

如果你正在寻找内存使用,差异在几乎每一种情况下都是微不足道的。对象是一个大于等效结构的指针。



更大的区别在于如何使用它们。对象可以有方法和层次结构,并与其余的Cocoa交互。使用struct,您需要为每个结构类型创建自定义函数或者将伪对象系统一起加入。除此之外,任意结构与其他Cocoa(Touch)不能很好地交互。例如:




  • 如果您在其中存储对象,则必须非常小心地正确进行自己的内存管理

  • 您不能在不创建对象包装器的情况下将它们存储在NSArrays中(因为NSArray是对象数组)

  • 不能在Interface Builder中挂钩结构 -



一般来说,如果你使用类似Cocoa的框架,对象是一个好的默认选择。使用结构体,一旦你确定你真的需要它们。


I'm developing an iPhone 3.1.3 application.

I have a class, called Object2D, with fields and methods; which represent a shape. Object2D has a field that represents its size, and another field that represent its type.

Now, I need another class called Pattern, which is a set of shapes. In Pattern I'm going to have an array of shapes. From these shapes I only need their size, their type and their location inside pattern, I don't need any method.

I'm wondering it is better to have a new struct that represent a shape instead of using Object2D class.

I ask this because I think on memory performance. I'm not sure, but struct are smaller than classes and maybe it's better to use them instead of classes.

What do you think?

解决方案

If you're looking at memory use, the difference is truly negligible in almost every situation. Objects are one pointer bigger than an equivalent struct.

The greater difference is in how you can use them. Objects can have methods and hierarchies and interact with the rest of Cocoa. With structs, you need to make custom functions for each struct type or hack together a pseudo-object system. On top of that, arbitrary structs don't interact well with the rest of Cocoa (Touch). For example:

  • If you store objects in them, you have to be very careful to do your own memory management correctly
  • You can't store them in NSArrays without creating an object wrapper (since NSArray is an array of objects)
  • You can't hook structs up in Interface Builder — it doesn't know anything about them
  • You can't do KVO or KVC with structs

In general, if you're working with a Cocoa-like framework, objects are a good default choice. Use structs once you've decided you really need them.

这篇关于结构或类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆