objective-c – 有没有理由不返回一个不可预期的可变对象?

objective-c – 有没有理由不返回一个不可预期的可变对象?,第1张

概述我有许多类似于以下的功能: + (NSArray *)arrayOfSomething{ NSMutableArray *array = [NSMutableArray array]; // Add objects to the array return [[array copy] autorelease];} 我的问题是关于这个方法的最后一行:返回可变对象并避免复 我有许多类似于以下的功能:
+ (NSArray *)arrayOfSomething{    NSMutableArray *array = [NSMutableArray array];    // Add objects to the array    return [[array copy] autorelease];}

我的问题是关于这个方法的最后一行:返回可变对象并避免复制 *** 作或返回不可变副本是否更好?是否有任何充分的理由避免返回一个不可预期的可变对象?

(我知道返回NSMutableArray是合法的,因为它是NSArray的子​​类.我的问题是这是否是一个好主意.)

解决方法 这是一个复杂的话题.我认为最好将您推荐给 object mutability的Apple指南.

关于使用内省来确定返回对象的可变性,Apple有这个说法:

To determine whether it can change a received object,the receiver must rely on the formal type of the return value. If it receives,for instance,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 read a property List from a file. When the Foundation framework processes the List it notices that varIoUs subsets of the property List are IDentical,so it creates a set of objects that it shares among all those subsets. Afterwards you look at the created property List objects and decIDe to mutate one subset. Suddenly,and without being aware of it,you’ve changed the tree in multiple places.

You ask NSVIEw for its subvIEws (subvIEws method) and it returns an object that is declared to be an NSArray but which Could be an NSMutableArray internally. Then you pass that array to some other code that,through introspection,determines it to be mutable and changes it. By changing this array,the code is mutating NSVIEw’s internal data structures.

鉴于上述情况,你可以完全接受在你的例子中返回可变数组(前提是,在返回之后你永远不会自己改变它,因为那样你就会违反合同).

话虽如此,几乎没有人读过Cocoa Objects GuIDe的那一部分,所以防御性编程会要求你制作一个不可变的副本并返回,除非性能分析表明这是一个问题.

总结

以上是内存溢出为你收集整理的objective-c – 有没有理由不返回一个不可预期的可变对象?全部内容,希望文章能够帮你解决objective-c – 有没有理由不返回一个不可预期的可变对象?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1238479.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-06
下一篇 2022-06-06

发表评论

登录后才能评论

评论列表(0条)

保存