【學習筆記】【OC語言】類方法,學習筆記oc語言

來源:互聯網
上載者:User

【學習筆記】【OC語言】類方法,學習筆記oc語言

1.基本概念
直接可以用類名來執行的方法(類本身會在記憶體中佔據儲存空間,裡面有類\對象方法列表)

2.類方法和對象方法對比
1>對象方法
以減號-開頭
只能讓對象調用,沒有對象,這個方法根本不可能被執行
對象方法能訪問執行個體變數(成員變數)

2>類方法
以加號+開頭
只能用類名調用,對象不能調用
類方法中不能訪問執行個體變數(成員變數)
使用場合:當不需要訪問成員變數的時候,盡量用類方法
類方法和對象方法可以同名

3.代碼

 1 #import <Foundation/Foundation.h> 2 /* 3  對象方法 4  1> 減號 - 開頭 5  2> 只能由對象來調用 6  3> 對象方法中能訪問當前對象的成員變數(執行個體變數) 7   8  類方法 9  1> 加號 + 開頭10  2> 只能由類(名)來調用11  3> 類方法中不能訪問成員變數(執行個體變數)12  13  14  類方法的好處和使用場合15  1> 不依賴於對象,執行效率高16  2> 能用類方法,盡量用類方法17  3> 場合:當方法內部不需要使用到成員變數時,就可以改為類方法18  19  可以允許類方法和對象方法同名20  */21 22 23 @interface Person : NSObject24 {25     int age;26 }27 28 // 類方法都是以+開頭29 + (void)printClassName;30 31 - (void)test;32 + (void)test;33 34 @end35 36 @implementation Person37 38 + (void)printClassName39 {40     // error:instance variable 'age' accessed in class method41     // 執行個體變數age不能在類方法中訪問42     //NSLog(@"這個類叫做Person-%d", age);43 }44 45 - (void)test46 {47     NSLog(@"111-%d", age);48     49     //[Person test];50 }51 52 + (void)test53 {54     // 會引發死迴圈55     //[Person test];56     57     NSLog(@"333");58     59     // 會引發死迴圈60 //    /[Person test];61 }62 63 @end64 65 int main()66 {67     //[Person printClassName];68     69     [Person test];70     71     //Person *p = [Person new];72     //[p test];73     74     /*75      -[Person printClassName]: unrecognized selector sent to instance 0x7fa520c0b37076      */77     // 系統會認為現在調用的printClassName是個對象方法78     //[p printClassName];79     80     return 0;81 }

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.