Obj-c物件導向

來源:互聯網
上載者:User
類的定義:          //類變數          static int count;
@interface Myobject:NSObject{          //主要進行成員變數的定義     NSString *param;     }     //主要進行成員方法的定義(不會有方法的實現)     -(void) run:(long) time name:(NSString*) name;          //屬性(setter,getter的簡化)     @property(copy,readwrite) NSString *param;
@end@implementation Myobject     //屬性群組合     @synthesize param;     //方法的實現     -(void) run:(long) time name:(NSString*) name{          // do something     }@end訊息發送 [myobject run:1098 name:@"Me"]屬性訪問myobject.param成員變數的訪問myobject->param屬性參數說明:執行個體建構函式

- (id) init{     self = [super init];     if(self){          //do something     }     return self;}類建構函式//類載入時會調用,並且只調用一次+(void) initialize{     //do something}//只有變數具有存取權限修飾符,方法不具有@public     隨處可以訪問@private     只有本類可以訪問@protected     本類和子類可以訪問id是泛類型,可以存放各種類型資料,使用id類型也就是使用"動態類型"

id類型是在執行時,動態判斷出id類型實際代表的類型,而不是自動的轉換成相應的類型靜態類型可以在編譯階段發現錯誤並且可讀性更好id類型具有很好的靈活性,但是在運行階段才能發現錯誤,很難控制

分類

     當需要擴充一個類的功能時可以用分類,另外也可以用繼承     是一種動態類型機制,動態綁定機制
@interface NSString(reverse)     -(NSString*) reverseString;     @end@implementation NSString(reverse)    -(NSString*) reverseString{          // do something     }@end
協議     只負責方法的定義,沒有m檔案;類似於java中的介面,但協議中沒有成員變數     定義的方法分為必須實現的方法,和不強制要求實現的方法          // 協議     @protocol Shape          -(void) draw;          @end     //協議實現(可以實現多個協議,用逗號分開)     @interface Rectangle:NSObject<Shape,...>          -(void) draw;     @end          // m檔案中必須實現協議中的方法     @implementation Rectangle          @required // 必須實現          -(void) draw{               // do something          }          @optional //可選     @end     //動態類型,區別於java的寫法     id<Shape> rect = [[Rectangle alloc] init];     兩個重要的協議          NSCopying               對象要進行copy必須實現的協議          NSCoding               對象想序列化需實現該協議

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.