Objective-C中一些關(guān)鍵字 學(xué)好必知
本文介紹的是Objective-C中一些關(guān)鍵字 學(xué)好必知,本文屬于幫助性質(zhì)的一片文章,幫助快速有效的去學(xué)習(xí)Objective-C,先來看內(nèi)容。
關(guān)于變量的作用域
- protected —Methods defined in the class and any subclasses can directly access the instance variables that follow.This is the default case.
該類和所有的子類中的方法可以直接訪問這樣的變量,這是默認(rèn)的。
- 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.
對(duì)于64位圖像,這樣的成員變量可以在實(shí)現(xiàn)這個(gè)類的圖像中隨意訪問。
全局變量(extern)
在程序的開始處,沒有在一個(gè)方法里面寫了
- int gMoveNumber=0;
那么我們說這個(gè)變量就是全局變量,也就是說在這個(gè)模塊中的任何位置可以訪問這個(gè)變量。
這樣的變量也是外部全局變量,在其他文件中也可以訪問它。但是訪問的時(shí)候要重新說明下這個(gè)變量,說明的方法是:
- extern int gMoveNumber;
當(dāng)然我們也可以在聲明的時(shí)候加上extern關(guān)鍵字。
- extern int gMoveNumber=0;
這樣的話在其他的類中使用還是需要重新說明一下了,而且這時(shí)候編譯器會(huì)給出警告。
如果這個(gè)全局變量只是在自己的類中使用,或者其他的類使用的它情況也比較小,那么我們把它定義成第一種情況,如果在外部文件使用的也比較多的話,那么我們把它定義成第二種情況。
這種定義其實(shí)違背了封裝性。
靜態(tài)變量(static)
因?yàn)槿肿兞渴侨值模绊懛庋b,所以有時(shí)候要用靜態(tài)變量。
- static int gMoveNumber;
這是這個(gè)變量是這個(gè)類中的靜態(tài)變量。如果不定義初始值的話為零。
如果靜態(tài)變量定義在方法中,那么這個(gè)變量在方法執(zhí)行完之后還是有效的,如果在第一次調(diào)用的時(shí)候改變了這個(gè)變量的值,那么在第二次調(diào)用的時(shí)候,這個(gè)變量的值是被改變過的值。
如果被定義在類中,那么這種改變也是有效的,就是作用域發(fā)生了改變。一個(gè)在方法中,一個(gè)在類中。
- atomic和nonatomic
nonatomic是告訴系統(tǒng)不要使用mutex(互斥)鎖定。這種鎖定會(huì)導(dǎo)致系統(tǒng)的性能低下,所以一般在多線程的時(shí)候使用atomic,平時(shí)多數(shù)用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;
小結(jié):關(guān)于Objective-C中一些關(guān)鍵字 學(xué)好必知的內(nèi)容介紹完了,希望本文對(duì)你有所幫助!