对象和方法之间的关系
(1)对象作为方法的参数
(2)对象作为方法的返回值
具体的关系请见下面程序示例:
#import <Foundation/Foundation.h>
typedef enum{white,yellow,hua,black} Color;
typedef enum{gong,mu} Sex;
#pragma 狗类的定义
@interface Dog:NSObject{
@public
Color _color;
float _weight;
Sex _sex;
int _speed;
}
-(void)eat:(NSString *)foodNum;
-(void)run;
-(void)print;
-(BOOL)isCompareColorWithOther:(Dog *)dog;
-(int)isCompareSpeedWithOther:(Dog *)dog;
@end
#pragma 狗类的实现
@implementation Dog
-(void)eat:(NSString *)foodNum{
_weight =_weight+0.5;
NSLog(@"狗吃了%@",foodNum);
}
-(void)run{
_weight -= 0.5;
NSLog(@"狗往前跑");
}
-(void)print{
NSLog(@"狗当前的体重为:%.2f",_weight);
}
-(BOOL)isCompareColorWithOther:(Dog *)dog{
if (_color == dog->_color)
{
return YES;
}
else
return NO;
}
-(int)isCompareSpeedWithOther:(Dog *)dog{
return _speed - dog->_speed;//对象差作为对象方法的返回值
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
Dog *d1 = [Dog new];//创建一个对象
d1->_color = yellow;
d1->_weight = 20;
d1->_sex = gong;
d1->_speed = 80;
[d1 eat:(@"一个玉米")];
[d1 run];
[d1 print];
Dog *d2 = [Dog new];//创建另一个对象
d2->_color = white;
d2->_weight = 30;
d2->_sex = mu;
d2->_speed = 60;
[d2 eat:(@"一个红薯")];
[d2 run];
[d2 print];
BOOL isSameColor = [d1 isCompareColorWithOther:d2];//比较狗毛颜色,d2作为方法的参数
int isSameSpeed = [d1 isCompareSpeedWithOther:d2];//计算d1和d2速度差,d2作为方法的参数
NSLog(@"d1与d2狗毛颜色相等与否=%d",isSameColor);
NSLog(@"d1与d2狗的速度差=%d",isSameSpeed);
}
return 0;
}
分析:上面程序很好的说明了对象和方法之间的关系。 |
|