Person.h
#import <Foundation/Foundation.h> @interface Person : NSObject { @public int _age; float _weight; // 運動1次,就去吃飯. } // 讓人運動 - (void)sport; // 讓人吃 - (void)eat; // 讓人運動 + (void)sport; // 讓人吃 + (void)eat; //對象方法 - (void)study; //類方法 + (void)study; @end
Person.m
#import "Person.h" @implementation Person // 讓人運動 - (void)sport { NSLog(@"這個人運動--對象方法"); // 在對象方法當中調用類方法 [Person eat]; } // 讓人吃 - (void)eat { NSLog(@"這個人吃東西--對象方法"); } // 讓人運動 + (void)sport { NSLog(@"這個人運動--類方法"); // 在本方法中,不能用self調用自己的方法.會死循環. [self sport]; } // 讓人吃 + (void)eat { NSLog(@"這個人吃--類方法"); } //對象方法 - (void)study { NSLog(@"%d年齡的人學習--對象方法",_age); } //類方法 + (void)study { NSLog(@"類方法"); } @end
/** 類方法:由類調用的方法 1.類方法的局限性: 不能訪問成員變量. 2.類方法的優勢: 不依賴對象.不占用內存空間.節約內存可以不創建對象。 3.對比對象方法和類方法 1)格式: 對象方法: - (返回值類型)方法名:(參數類型)參數名稱; 類方法: + (返回值類型)方法名:(參數類型)參數名稱; 2)調用者 對象方法:必須創建對象,由對象來調用. 類方法:不依賴於對象,由類直接調用. 練習:設計1個計算器,有加法\減法\乘法\除法,用類方法不依賴於對象. 報錯信息: unrecognized selector sent to class 0x1000046c8 某個方法找不到. */