gpt4 book ai didi

objective-c - 最佳实践 : Return mutableArray. 复制或 nsmutableArray 如果返回类型是 NSArray

转载 作者:行者123 更新时间:2023-12-05 08:27:56 25 4
gpt4 key购买 nike

- (NSArray *)map:(id (^)(id))block {
NSEnumerator * enumerator = self.objectEnumerator;
NSMutableArray * array = [NSMutableArray array];
id obj;
while ((obj = enumerator.nextObject)) {
[array addObject:(block(obj) ?: [NSNull null])];
}
return array (NSMutableArray *); or return array.copy (NSArray *)
}

这是 NSArray 上的一个类别

最佳答案

来自 Receiving Mutable Objects :

Use Return Type, Not Introspection

To determine whether it can change a received object, the receiver of a message must rely on the formal type of the return value. If it receives, for example, an array object typed as immutable, it should not attempt to mutate it. It is not an acceptable programming practice to determine if an object is mutable based on its class membership.

[…]

You should not make assumptions about whether an object is mutable based on class membership. Your decision should be guided solely by what the signature of the method vending the object says about its mutability. If you are not sure whether an object is mutable or immutable, assume it’s immutable.

一般来说:

  • 如果您的调用者遵循这些准则,只需返回可变数组,因为它稍微便宜一些,并且调用者不会改变它。

  • 如果您不确定调用者是否可能不遵循这些准则,并且您想编写防御性代码,请使用 array.copy 返回一个不可变副本。

特定于这种情况,这无关紧要,因为即使调用者改变它,您也永远不会再使用该数组实例。

关于objective-c - 最佳实践 : Return mutableArray. 复制或 nsmutableArray 如果返回类型是 NSArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27389591/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com