Differences between [NSArray arrayWithArray:] and [NSArray copy]

前端 未结 7 2052
清歌不尽
清歌不尽 2021-02-12 13:50

lately I work much with arrays and I\'m wonder.. what\'s diffrences between those two lines.

NSArray *array = [NSArray arrayWithArray:someArray];
7条回答
  •  日久生厌
    2021-02-12 14:18

    The main difference is that -copy knows better how to copy itself (can do it more efficiently and maybe use a more adapted subclass of NSArray) while +arrayWithArray: will create a new instance of NSArray (well, in fact the concrete class used by Foundation for arrays) and feed it with the same list of objects from the initial object. Also it will add an extra autorelease.

    So -copy is (very very) likely more efficient.

    In fact for immutable NSArrays, -copy is just doing -retain, so it does not even bother creating a new instance.

提交回复
热议问题