2015-07-20 59 views
0

今天我的學生中有一位問我什麼是這兩個概念常量/變量和不可變/易變

  1. 常量和變量
  2. 非易變和易變

之間的技術差異因爲我們知道常量是不可變的,變量是可變的。我告訴他Mutable/Non Mutable是Cocoa Framework的概念,而Constants/Variable則不是。但我不知道我是對的

我知道它的用法,但沒有找到任何適當的技術答案。

回答

0

你說的常量是不可變的,變量是可變的。

可可框架中的mutable vs non-mutable通常與數據結構(例如數組,隊列,字典等)有關係。

凡可變意味着我們可以改變數據結構(添加/刪除對象)和不可變的手段,我們不能修改它(只讀)。

希望這有助於

0

常量性目標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)對象來說,不變性也很重要,並不像它應該那樣經常考慮。特別是對於傳遞的「數據類」,應該考慮一個不可變的版本使事情變得更容易。這也適用於你自己的課程。