arrayWithCapacity是NSArray.h中定义的方法,在NSArray.m中实现
当我查看GNUStep提供的代码时,我可以得到arrayWithCapacity是一个调用initWithCapacity的常规方法:
+ (id) arrayWithCapacity: (NSUInteger)numItems { return AUTORELEASE([[self allocWithZone: NSDefaultMallocZone()] initWithCapacity: numItems]); }
initWithCapacity是一个只进行自我初始化的简单方法.
- (id) initWithCapacity: (NSUInteger)numItems { self = [self init]; return self; }
没有关于内存分配和执行的项目数量.
使用arrayWithCapacity方法有什么好处?简单地使用[[NSArray alloc] init]会更好吗?
解决方法
期望提供显式大小可以改善内存分配,因为在添加项目时无需调整数组的大小.在实践中,它只是一个提示,并且有一些证据表明它实际上没有使用(参见基金会集合类的
objc.io article).