Become a MacRumors Supporter for $25/year with no ads, private forums, and more!
  • Did you order new AirTags? We've opened a dedicated AirTags forum.

ArtOfWarfare

macrumors G3
Original poster
Nov 26, 2007
9,120
5,075
I have a struct called Circle (it has members x, y, and r). I define it and give a few function declarations in a Circle.h file and define those functions in a Circle.m file.

I did it this way just because that's how CGRects are done.

But then it occurred to me that this is an awful lot like a class. Is there any real reason that I should or shouldn't make this a class? If I shouldn't make this a class, I'm kind of wondering why I should make anything a class.

Thoughts?
 

PhoneyDeveloper

macrumors 68040
Sep 2, 2008
3,114
93
I really don't know why Core Graphics is a C API. The usual reason these days to have a C API would be to allow access from multiple computer languages. If you don't have that requirement and it makes more sense to build a class then do it.
 
Comment

ArtOfWarfare

macrumors G3
Original poster
Nov 26, 2007
9,120
5,075
One con of using a class (in Obj-C):
Struct instances can be placed on the stack or heap. Class instances can only go on the heap.

By extension, I must alloc and init if I'm using a class whereas if I'm using a struct I may not have to - I feel like this might result in some minor performance benefits when using structs. Currently, in my code using my circles, I haven't had to call alloc or malloc or calloc or any other memory function yet.

I have thought of a few things that classes offer out of the box that I couldn't trivially replicate with structs (like delegation,) but I still haven't yet thought of a reason to make my circles be instances of a class instead of a struct.
 
Comment

PhoneyDeveloper

macrumors 68040
Sep 2, 2008
3,114
93
If your struct/class were to have a data member that was an object, like NSString, then you would want a class. If it will be only POD types (plain old data) then you could stick with the struct.

If you pass the struct by value to/from methods that might have poorer performance than the class, which will only take up four bytes.

I wouldn't use performance as the number one reason to use a struct over a class, although it could contribute.
 
Comment

ArtOfWarfare

macrumors G3
Original poster
Nov 26, 2007
9,120
5,075
What do you do when you want to have a collection of Circles?

I have a C array + an int tracking the size of the array. Order of the circles doesn't matter so inserts and deletes are pretty easy (swap the object you want to remove with the last one, reduce the int tracking the size... Inserts just always go at the end.)

Oh, I just realized why you're asking - NSArrays only hold NSObjects.
 
Comment
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.