Main.m
#import <Foundation/Foundation.h>
#import "Person.h"
#import "Dog.h"
int main(int argc, const char * argv[])
{
Dog *dahuang = [[Dog alloc] initWithName:@"大黄" withColor:@"黑色"];
Person *person = [[Person alloc] init];
// [person setDog:dahang];
// [person setName:@"Jack"];
//等价的点语法
person.dog = dahuang;
person.name = @"jack";
int time;
while (1) {
NSLog(@"请输入时间:");
scanf("%d",&time);
[person playDog:time];
}
return 0;
}
Dog.h
@interface Dog : NSObject {
NSString *_name; //名字
NSString *_color; //颜色
}
//自定义初始化方法
- (id)initWithName:(NSString *)name withColor:(NSString *)color;
//跑
- (void)run;
//捡球
- (void)playBall;
//叫
- (void)bark;
Dog.m
//自定义初始化方法
- (id)initWithName:(NSString *)name withColor:(NSString *)color {
self = [super init];
if (self != nil) {
_name = name;
_color = color;
}
return self;
}
//跑
- (void)run {
NSLog(@"颜色是%@的%@在跑",_color,_name);
}
//捡球
- (void)playBall {
NSLog(@"颜色是%@的%@在捡球",_color,_name);
}
//叫
- (void)bark {
NSLog(@"颜色是%@的%@在叫",_color,_name);
}
Person.h
@interface Person : NSObject {
NSString *_name; //人的名字
Dog *_dog; //狗
}
//设置器
- (void)setName:(NSString *)name;
- (void)setDog:(Dog *)dog;
//遛狗的方法
- (void)playDog:(NSInteger)time;
Person.m
//设置器
- (void)setName:(NSString *)name {
_name = name;
}
- (void)setDog:(Dog *)dog {
_dog = dog;
}
//遛狗的方法
- (void)playDog:(NSInteger)time {
switch(time)
{
case 9:
{
[_dog run];
break;
}
case 10:
{
[_dog playBall];
break;
}
case 11:
{
[_dog bark];
break;
}
default:
{
NSLog(@"休息...");
break;
}
}
// if (time == 9) {
// //跑
// [_dog run];
// }else if (time == 10) {
// //捡球
// [_dog playBall];
// }else if (time == 11) {
// //叫
// [_dog bark];
// }else {
// NSLog(@"休息...");
// }
}