简体   繁体   English

快速 NSMutableArray 问题

[英]Quick NSMutableArray Question

I was wondering, would using a NSMutableArray be the best way for making an array that i will be adding objects to?我想知道,使用 NSMutableArray 是制作我将添加对象的数组的最佳方式吗? Or, just a regular NSArray?或者,只是一个普通的 NSArray? secondly, I'm trying to make something sort of like an ArrayList in java (so there is no limit to the size), and I would like to know how to do that.其次,我正在尝试在 java 中制作类似于 ArrayList 的东西(因此对大小没有限制),我想知道该怎么做。 What I've thought of is to make a bigger array and copy older array into it.我想到的是制作一个更大的数组并将旧数组复制到其中。 My code:我的代码:

- (void) addAccount:(BankAccount *)b
{

accountCount = [NSNumber numberWithDouble:[accountCount doubleValue] + 1];    
NSMutableArray *oldList = accounts;
accounts = [[NSMutableArray alloc] (some code to make bigger and copy over)];

}

PS I taught myself this language yesterday, so I may not understand you response if it's too advanced PS我昨天自学了这门语言,所以如果太高级我可能听不懂你的反应

The difference between an NSMutableArray and an NSArray lies in the meaning of the word "mutable". NSMutableArrayNSArray之间的区别在于“可变”一词的含义。 ie: A mutable array can be modified after it's created whereas a "normal" NSArray is immutable and can't be modified after it's created.即:可变数组在创建后可以修改,而“普通” NSArray 是不可变的,创建后无法修改。

As such, using an NSMutableArray and adding objects to it via the addObject: method would seem an ideal solution.因此,使用NSMutableArray并通过addObject:方法向其中添加对象似乎是一个理想的解决方案。

NSMutableArrays are what you want. NSMutableArrays 是你想要的。 Also, NSMutableArrays are already like ArrayLists or STL vectors, or anything else with "no limit to the size".此外,NSMutableArrays 已经像 ArrayLists 或 STL 向量,或任何其他“没有大小限制”的东西。 You can say [myArray addObject:someObject];你可以说[myArray addObject:someObject]; until you run out of memory, and it will just keep resizing itself as needed.直到你用完 memory,它会根据需要不断调整自己的大小。

  1. If you want to be adding objects all at once use NSArray .如果您想一次添加所有对象,请使用NSArray If you're going to be adding some objects now, then more later, use NSMutableArray .如果您现在要添加一些对象,稍后再添加,请使用NSMutableArray
  2. Your code snippet doesn't make much sense.您的代码片段没有多大意义。 To make an NSMutableArray , do this:要制作NSMutableArray ,请执行以下操作:

    NSMutableArray *array = [NSMutableArray array];

If you don't need an order (normally you don't), use a NSSet/NSMutableSet.如果您不需要订单(通常不需要),请使用 NSSet/NSMutableSet。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM