今天我的学生中有一位问我什么是这两个概念常量/变量和不可变/易变
- 常量和变量
- 非易变和易变
之间的技术差异因为我们知道常量是不可变的,变量是可变的。我告诉他Mutable/Non Mutable是Cocoa Framework的概念,而Constants/Variable则不是。但我不知道我是对的
我知道它的用法,但没有找到任何适当的技术答案。
今天我的学生中有一位问我什么是这两个概念常量/变量和不可变/易变
之间的技术差异因为我们知道常量是不可变的,变量是可变的。我告诉他Mutable/Non Mutable是Cocoa Framework的概念,而Constants/Variable则不是。但我不知道我是对的
我知道它的用法,但没有找到任何适当的技术答案。
你说的常量是不可变的,变量是可变的。
可可框架中的mutable vs non-mutable通常与数据结构(例如数组,队列,字典等)有关系。
凡可变意味着我们可以改变数据结构(添加/删除对象)和不可变的手段,我们不能修改它(只读)。
希望这有助于
常量性目标C referes对象引用,但从来没有对象(如即在C++)。可变性是指对象。
// non-const reference to immutable string object
NSString *s = …;
// You can change the reference, …
s = …; // No error
// … but not the string object
[s appendString:…]; // Error
// const reference to immutable string object
const NSString* s = …;
// You can neither change the reference, …
s = …; // Error
// … nor the string object
[s appendString:…]; // Error
// non-const reference to mutable string object
NSMutableString *s = …;
// You can change the reference …
s = …; // No Error
// … and the string object
[s appendString:…]; // No error
// const reference to mutable string object
const NSMutableString *s = …;
// You cannot change the reference, …
s = …; // Error
// … but the string object
[s appendString:…];
所以你可以说不变性是“(OOP)对象的常量”。
然而,“变量”(更准确地说:C对象不包含Objective-C对象)的常量对编译器来说是非常重要的,因为它是SSA。不变性对于设计中的许多事物都很重要。
即使对于(Objective-C)对象来说,不变性也很重要,并不像它应该那样经常考虑。特别是对于传递的“数据类”,应该考虑一个不可变的版本使事情变得更容易。这也适用于你自己的课程。