Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C Class or struct?

I have a class Song with properties Title, Key, Artist, etc. There are no methods. I loop through a database of song information and create a Song object for each, populating the properties, and then store the Song objects in an NSArray.

Then I thought, why not just have a struct Song with all those same properties instead of a class Song. Doing so would eliminate the class files, the #import Song line in the using class's .m file, and the need to alloc, init, release.

On the other hand, I'd have to put the struct definition in every class that might need it. (Unless there's some globally accessible location -- is there?) Also, can a struct be stored in an NSArray?

like image 680
Scott Pendleton Avatar asked Apr 02 '10 14:04

Scott Pendleton


3 Answers

I would do it with a class. A struct cannot be stored in an NSArray (or any of the other container classes for that matter), unless you wrap it in a NSValue, which can be done but is a bit fiddly.

Plus, as you have pointed out, you have to define the struct somewhere. The normal way would be to define it in a header (.h) file just as for a class. So there's no 'gain' from a struct there.

like image 105
Nick Moore Avatar answered Oct 20 '22 15:10

Nick Moore


You can't store structs in an NSArray (look at the signatures of its methods — they all take and return objects). But besides that, as I said in the answer to another recent question, putting objects in structs is just about always a bad idea. Objects need to be retained and released and structs don't have code associated with them to ensure that happens at the right times. This makes more sense as a model object.

like image 34
Chuck Avatar answered Oct 20 '22 15:10

Chuck


It could go both ways but why not separate your concerns and keep it in it's own class file? Plus, doing so is more in line with the Single Responsibility Principle of SOLID. Why give your main class file another reason to change? Break it out.

like image 2
Brian David Berman Avatar answered Oct 20 '22 15:10

Brian David Berman