简体   繁体   中英

initWithCapacity: in NSArray

initWithCapacity: is declared in NSMutableArray , but I want to use it to initialize an NSArray . I there any solution?

Since NSArray objects are immutable (cannot change the objects they contain) there's no use in adjusting the capacity of NSArray s.

The capacity is the number of objects an array can contain without reallocating memory. It is only used for optimization.

It doesn't make sense to init an NSArray using initWithCapacity: , because you can't subsequently add objects. An NSArray with no objects in has a de facto capacity of 0. What are you really trying to achieve?

Just make an NSMutableArray with initWithCapacity: , fill it with stuff, and then make an NSArray from it.

You can use either:

NSArray *_immutableArray = [_mutableArray copy];
...
[_immutableArray release];

Or:

NSArray *_immutableArray; 
[_immutableArray initWithArray:_mutableArray];
...
[_immutableArray release];

Or:

NSArray *_immutableArray = [NSArray arrayWithArray:_mutableArray];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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