Objective C类或结构? [英] Objective C Class or struct?

查看:94
本文介绍了Objective C类或结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类Song,其中包含Title,Key,Artist等等。没有方法。我循环遍历一个歌曲信息数据库,并为每个对象创建一个Song对象,填充属性,然后将Song对象存储在NSArray中。

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.

然后我想,为什么不只是一个结构歌曲与所有那些相同的属性,而不是一个类宋。这样做会删除类文件,使用类的.m文件中的#import Song行,以及需要alloc,init,release。

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?

推荐答案

我可以将结构存储在NSArray中吗?会做一个类。一个struct不能存储在NSArray(或任何其他容器类)中,除非你将它包装在一个NSValue,这可以做,但有点fiddly。

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.

另外,正如你所指出的,你必须在某处定义struct。正常的方式是在头文件(.h)文件中定义它,就像一个类一样。所以没有从结构的增益。

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.

这篇关于Objective C类或结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆