Objective-C中一些關鍵字 學好必知
本文介紹的是Objective-C中一些關鍵字 學好必知,本文屬于幫助性質的一片文章,幫助快速有效的去學習Objective-C,先來看內容。
關于變量的作用域
- protected —Methods defined in the class and any subclasses can directly access the instance variables that follow.This is the default case.
該類和所有的子類中的方法可以直接訪問這樣的變量,這是默認的。
- private —Methods defined in the class can directly access the instance variables that follow, but subclasses cannot.
該類中的方法可以訪問這樣的變量,子類不可以。
- public —Methods defined in the class and any other classes or modules can di- rectly access the instance variables that follow.
除了自己和子類中的方法外,也可以被其他類或者其他模塊中的方法所訪問。開放性最大。
- package —For 64-bit images, the instance variable can be accessed anywhere within the image that implements the class.
對于64位圖像,這樣的成員變量可以在實現這個類的圖像中隨意訪問。
全局變量(extern)
在程序的開始處,沒有在一個方法里面寫了
- int gMoveNumber=0;
那么我們說這個變量就是全局變量,也就是說在這個模塊中的任何位置可以訪問這個變量。
這樣的變量也是外部全局變量,在其他文件中也可以訪問它。但是訪問的時候要重新說明下這個變量,說明的方法是:
- extern int gMoveNumber;
當然我們也可以在聲明的時候加上extern關鍵字。
- extern int gMoveNumber=0;
這樣的話在其他的類中使用還是需要重新說明一下了,而且這時候編譯器會給出警告。
如果這個全局變量只是在自己的類中使用,或者其他的類使用的它情況也比較小,那么我們把它定義成第一種情況,如果在外部文件使用的也比較多的話,那么我們把它定義成第二種情況。
這種定義其實違背了封裝性。
靜態變量(static)
因為全局變量是全局的,影響封裝,所以有時候要用靜態變量。
- static int gMoveNumber;
這是這個變量是這個類中的靜態變量。如果不定義初始值的話為零。
如果靜態變量定義在方法中,那么這個變量在方法執行完之后還是有效的,如果在第一次調用的時候改變了這個變量的值,那么在第二次調用的時候,這個變量的值是被改變過的值。
如果被定義在類中,那么這種改變也是有效的,就是作用域發生了改變。一個在方法中,一個在類中。
- atomic和nonatomic
nonatomic是告訴系統不要使用mutex(互斥)鎖定。這種鎖定會導致系統的性能低下,所以一般在多線程的時候使用atomic,平時多數用nonatomic。
- @synthesize和@dynamic
- @synthesize will generate getter and setter methods for your property.
- @dynamic just tells the compiler that the getter and setter methods are implemented not by the
- class itself but somewhere else (like the superclass)
- Uses for @dynamic are e.g. with subclasses of NSManagedObject (CoreData) or when you want to create an
- outlet for a property defined by a superclass that was not defined as an outlet:
- Super class:
C代碼
- @property(nonatomic, retain)NSButton* someButton;
- ...
- @synthesize someButton;
- @property(nonatomic, retain)NSButton* someButton;
- ...
- @synthesize someButton;
- Subclass:
- C代碼
- @property(nonatomic, retain)NSButton* someButton;
- ...
- @dynamic someButton;
小結:關于Objective-C中一些關鍵字 學好必知的內容介紹完了,希望本文對你有所幫助!