开发者

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开发者_如何学JAVA 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?


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜