NSArray size and mutability

最后都变了- 提交于 2020-01-05 09:45:14

问题


In Java, I commonly initialize arrays that are a specific size and then add and replace objects as my code goes on. In Objective C, I can't do that with an NSArray. Code that I have ported over from Java often has to use NSMutableArray, which I assume perform less efficent than NSArray. (My best guess as to how NSMutableArray stores it's members is using a linked list, but I could be wrong)

Are there any types of arrays for Objective C that have fixed sizes and allow changes within the array? Why is it not possible to replace objects at a certain object with NSArray? I can do this with C arrays, why not Objective C?


回答1:


Your assumption is wrong, NSMutableArray won't be any slower than a plain NSArray.

NSMutableArray is not going to use a linked list, it will use a dynamic array. It is every bit as fast as a plain array except on the insertions where it needs to resize. But since those get exponentially further apart, it amortizes to nearly the same, and identical if you don't hit a resize.

It's basically the same as Java's ArrayList.




回答2:


In Objective-C, many classes have mutable and immutable variants.There may be performance or memory benefits to immutable NSArrays, but if you require an array that can be modified, simply use an NSMutableArray. There's no reason to be alarmed or concerned. That's what they're there for.

You can initialize mutable arrays with intended capacities, though you are not forever bound to that capacity - the array will grow beyond capacity if necessary.

int numberOfItems = ...
NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:numberOfItems];

Any optimization benefit available to NSArray is contingent on the fact that it is immutable. So syntax aside, you can't realize the benefits of an immutable object when what you need to actually use is mutable (eg, you need to replace objects in your case).




回答3:


Don't assume NSMutableArray is too slow for you. Profile, don't speculate.

You might also check out NSPointerArray if you're developing a Mac OS X app. It's not available on iOS.




回答4:


You have to use NSMutableArray if you want to replace a certain object. And create the array using

 + (id)arrayWithCapacity:(NSUInteger)numItems   

or

- (id)initWithCapacity:(NSUInteger)numItems

of NSMutableArray and specify the size of the array.



来源:https://stackoverflow.com/questions/8252417/nsarray-size-and-mutability

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!