main.m
#import <Foundation/Foundation.h>
#import "Person.h"
#import "Calculator.h"
#import "Car.h"
#import "Dog.h"
int main(int argc, const char * argv[])
{
Person *p = [Person new];
[p run];
[Person run];
//? [Person print];
[p setAge:18];
[p age];
int a = [Calculator sumofNum1:52 andNum2:55];
NSLog(@"a = %d",a);
int b = [Calculator aveofNum1:66 andNum2:55];
NSLog(@"b = %d",b);
Car *c = [Car new];
[c setSpeed:50];
[c speed];
[c test];
[Car test];
Dog *d = [Dog new];
[d run];
//? [d bark];
return 0;
}
/*?
類方法:
1>只能以加號開頭
2>類方法只能由類調用
3>類方法不能訪問成員變量
對象方法:
1>以減號開頭
2>對象方法只能由對象調用
3>可以訪問成員變量
類方法的好處與使用的場合
1>不依賴對象渤刃,執(zhí)行效率比對象方法高(能用類方法盡量用類方法)
2>場合:不需要成員變量時,都使用類方法(工具類)
注意:對象方法和類方法可以同名,可以同時存在
*/
Person.h
#import <Foundation/Foundation.h>
@interface Person : NSObject
{
int _age;
}
- (void)run;
+ (void)run;
+ (void)print
{
NSLog(@"%d對象方法",_age);
}
- (void)setAge:(int)age;
- (int)age;
@end
Person.m
#import <Person.h>
@implementation Person
- (void)run
{
//? NSLog(@"%d類方法",_age);
//? 報錯暇昂,在類方法中不能訪問成員變量
NSLog(@"調用了-run方法");
//? [self run];? //? 死循環(huán)
[Person run];? //? 在對象方法中可以調用類方法,在類方法中不可以調用對象方法(類方法中沒有對象)
}
+ (void)run
{
NSLog(@"調用了+run方法");
//? [Person run];? //? 死循環(huán)
}
- (void)setAge:(int)age
{
_age = age;
}
- (int)age
{
return _age;
}
@end
/*
計算器類:
求和
求平均值
*/
Calculator.h
#import <Foundation/Foundation.h>
@interface Calculator : NSObject
+ (int)sumofNum1:(int)num1 andNum2:(int)num2;
+ (int)aveofNum1:(int)num1 andNum2:(int)num2;
@end
Calculator.m
#import <Calculator.h>
@implementation Calculator
+ (int)sumofNum1:(int)num1 andNum2:(int)num2
{
return num1 + num2;
}
+ (int)aveofNum1:(int)num1 andNum2:(int)num2;
//? self? 當前類
int sum = [self sumofNum1:num1 andNum2:num2];
return sum/2;
//? int sum = [Calculator sumofNum1:num1 andNum2:num2];
return sum/2;
//? return (num1 +num2)/2;
@end
//? self關鍵字
/*
self關鍵字的用途
1>self關鍵字可以用來訪問成員變量
2>調用當前的方法吱窝,self代表誰
1>>self出現(xiàn)在對象方法中:代表當前對象
2>>self出現(xiàn)在類方法中:代表當前類
調用方法的格式:[self 方法名];
*/
Car.h
#import <Foundation/Foundation.h>
@interface Car : NSObject
{
int _speed;
}
- (void)setSpeed:(int)speed;
- (int)speed;
- (void)test;
+ (void)test;
- (void)test1;
+ (void)test2;
@end
Car.m
#import <Car.h>
@implementation Car
- (void)setSpeed:(int)speed
{
_speed = speed;
}
- (void)speed
{
return _speed;
}
//? - (void)test
//? {
//? int _speed = 40;? //? 不知道_speed是誰
// NSLog(@"speed=%d",self->_speed);
//? NSLog(@"speed=%d",[self speed]);? //? 使用get方法
//? }
- (void)test
{
NSLog(@"調用了-test方法");
//? [self test];? //? 死循環(huán)
//? [Car test];
}
+ (void)test
{
NSLog(@"調用了+test方法");
//? [self test];? //? 死循環(huán)
}
- (void)test1
{
NSLog(@"abcd");
}
+ (void)test2
{
NSLog(@"1234");
}
@end
Dog.h
#import <Foundation/Foundation.h>
@interface Dog : NSObject
- (void)bark;
- (void)run;
@end
Dog.m
#import <Dog.h>
@implementation Dog
- (void)bark
{
NSLog(@"汪汪汪");
}
- (void)run
{
//? NSLog(@"汪汪汪");
//? self? 代表當前對象
[self bark];
NSLog(@"跑跑跑");
}
@end