I plan to define a class, that among its properties contains coordinates for an x/y grid. However, I'm unsure of the 'best' way to approach the design of this. It's a very simple issue, I just want to do it correctly and have a justification!
One solution would be to have to two properties, of type 'int
', one for x and one for y, within the object.
The other would be define a typedef struct of two ints containing x/y values and naming it <ClassPrefix>Coordinate
. Similar to CGSize
?
Are there any other/better ways to do this? Which is preferred? Not sure how to justify either way.
Thanks!
Tim.
It is a trade off.
A class and its instances will cost more in resource, especially when you have to make a lot of them. If there will not be so many instances, it is not a problem.
Structure is faster but it's difficult to extent and the most inconvenient thing is a struct can not hold objects or method.
For your example, if you just use it for coordinates, I suggest you to use struct. But it depends on your design and code. There is no absolute judgment which is best.
The answer to the "Which one is preferred?" question depends on a few factors:
struct
wins; if the answer is "fifty eight", object wins.struct
may be OK.struct
may be a better choice.struct
may be a better choice.Ultimately, your design constraints help you determine what's best; there is no data structure that is universally "better".
In addition to @dasblinkenlight answer, I'll give you some decision advices:
Is the structure immutable after creation?
Use an object.
Does the structure owns (= retains) pointers to other objects or arrays (both C arrays or
NSArray
)? Does it interact with objects (= has methods with object parameters)?Then use an object.
Does the structure contains only primitive types (
int
,float
, otherstruct
s etc) and it interacts only with other primitives/structs?Then use a
struct
with functions.