iOS 对象数组:在函数内创建对象数组
我有一个“Note”类,还有一个 Tuner 类。我的 Tuner 类正在其 init 函数中初始化一个 NSArray*
。
我想初始化这个数组来容纳 88 个音符,现在我正在创建像 Note* key1; 这样的东西。等等等等。
我只是确保我需要为这些注释分配东西,以便它们在初始化完成后不会超出范围,并且我的 NSArray
与其条目保持一致,或者我是能够只声明 Note key1 并插入到数组中,它就为我处理好了。 创建一个包含一些对象的 NSArray 的示例代码片段,使得即使在函数退出后该数组也能保留下来,这将非常有帮助。谢谢你!
I have a "Note" class, and I have a Tuner Class. My Tuner class is initializing an NSArray*
in it's init function.
I want to initialize this array to hold 88 notes, and right now I am creating things like Note* key1; etc etc.
I am just making sure that I need to alloc things for these notes so that they do not go out of scope once init finishes, and my NSArray
stays in tact with its entries, or am I able to just declare Note key1 and insert into the array and it is taken care of for me.
An example piece of code creating an NSArray
containing a few objects such that the array will stay around even after the function exits would be very helpful. Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
NSArray
和NSMutableArray
在添加对象时将-retain
发送给对象,因此适当的做法是-release
> 您显式添加的对象或使用自动释放的对象。下面是
Tuner
类的-init
方法的一个简单示例:您需要
+alloc
每个 Note 对象并-release it,因为将其添加到数组中会保留它。要在完成后销毁所有音符对象,请确保您的
Tuner
类在其-dealloc
方法中释放数组:NSArray
andNSMutableArray
send-retain
to objects when they are added, so the appropriate thing to do is to-release
the objects you add explicitly or use autoreleased objects.Here's a quick example for the
Tuner
class's-init
method:You will need to
+alloc
every Note object and-release
it, since adding it to the array retains it. To destroy all the note objects when you're done, make sure yourTuner
class releases the array in its-dealloc
method:下面是一个简单的示例,说明如何在
Tuner
类的 init 函数中执行此操作。请注意,在我的示例中,
myNotes
被假定为类型NSMutableArray
这是通过像这样单独添加对象来构造数组的唯一方法。Here's a simple example of how you might do that in the init function of your
Tuner
classPlease note that in my example,
myNotes
is assumed to be of the typeNSMutableArray
It is the only way you can construct an array by adding objects individually like that.在保存笔记数组的类中。
在创建数组的方法内部:
Inside the class which will hold the notes array.
Inside the method for creating the array:
好吧,我不完全确定你想做什么,但你可以将 NSMutableArray 作为全局变量。然后,您可以向该数组添加和删除任何类型的任何对象。该数组仍将位于内存中,直到您调用它的释放方法。
Well, I'm not totally sure what you are trying to do, but you could just make an NSMutableArray as a global variable. You could then add and remove any object of any type to this array. The array would still be in memory until you call it's release method.