Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

struct or class

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?

like image 755
VansFannel Avatar asked Jun 30 '11 05:06

VansFannel


1 Answers

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.

like image 86
Chuck Avatar answered Sep 23 '22 23:09

Chuck