views:

297

answers:

4

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?

+2  A: 

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.

Brian David Berman
Thanks, good point.
Scott Pendleton
+6  A: 

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.

invariant
Great, now I know.
Scott Pendleton
A: 

Also are you 100% sure that you won't need to add methods to each Song later?

I think stay with a class for the reasons @invariant said.

jamone
+2  A: 

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.

Chuck
Thanks, good point.
Scott Pendleton