在Objective C中有一个类似NSArray,NSDictionary等类的可变和不可变版本的逻辑是什么? [英] What is the logic behind having a mutable and immutable versions of classes like NSArray, NSDictionary etc in Objective C?

查看:165
本文介绍了在Objective C中有一个类似NSArray,NSDictionary等类的可变和不可变版本的逻辑是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么Objective C中的公共集合类(如NSString,NSArray,NSDictionary等)具有可变版本和不可变版本。分别定义它们的逻辑是什么?性能,内存管理还是其他什么?

Why do common collection classes in Objective C like NSString, NSArray, NSDictionary etc have a mutable as well as an immutable version. What is the logic behind defining them separately? Performance, memory management or anything else?

推荐答案

存在类的不可变版本,因为不可变对象本身就是唯一标识符特定的州。即如果您的 NSArray 为100 NSString 个实例,则 NSArray 实例可以被视为对这些字符串中的任何一个都是幂等的。

The immutable versions of the classes exist because an immutable object is, in and of itself, a unique identifier for a particular state. I.e. if you have an NSArray of 100 NSString instances, that NSArray instance can be treated as idempotent for any one of those strings.

同样,不变性意味着在州出售后不会发生变化。例如, NSView 子视图方法返回一个不可变数组,从而确保调用者不会播放有内容的游戏(甚至不能指望)。在内部, NSView 可以选择返回包含子视图的[可能] NSMutableArray(因为它在内部是可变的)并且转换为 NSArray 表示调用者无法在没有恶意强制转换或错误编译器警告的情况下操作内容。 (这可能是也可能不是真正的实现,顺便说一句 - 但这种模式在别处使用)。

As well, the immutability means that a change cannot happen after the state has been vended. For example, NSView's subviews method returns an immutable array, thus ensuring that the caller isn't going to play games with the contents (nor even expect to be able to). Internally, NSView could choose to return the [likely] NSMutableArray that contains the subviews (since it is internally mutable) and the typecast to NSArray means the caller can't manipulate the contents without an evil cast or bad compiler warning. (This may or may not actually be the real implementation, btw -- but this pattern is used elsewhere).

不变性也意味着枚举和/或遍历可以完成没有中间国家变化的风险。类似地,许多不可变类也显式线程安全;任意数量的线程都可以同时读取不可变状态,通常不需要锁定。

Immutability also means that enumeration and/or traversal can be done without risk of a state change in the middle. Similarly, many immutable classes are also explicitly thread safe; any number of threads can simultaneously read the immutable state, often without need for a lock.

这篇关于在Objective C中有一个类似NSArray,NSDictionary等类的可变和不可变版本的逻辑是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆