对象关系
依赖关系 A 对象作为 B 对象的局部变量或方法形参,则 B 依赖于 A
创建iPod类和Person类 iPod.h @interface iPod : NSObject { NSString * _name; } //封装_name成员变量 -(void)setName:(NSString *) name; -(NSString *)name;
//声明播放音乐方法 -(void)playMusic; @end iPod.m @implementation iPod -(void)setName:(NSString *) name{
_name = name; } -(NSString *)name{
return _name; }
-(void)playMusic{
NSLog(@"\n%@播放歌曲----------------------------------",_name); } @end
Person.h #import "iPod.h" @interface Person : NSObject { NSString * _name; }
//封装_name成员变量 -(void)setName:(NSString *) name; -(NSString *)name;
//ipod对象作为person对象的listenMusic方法的形参 -(void) listenMusic:(iPod *) ipod; @end Person.m @implementation Person -(void)setName:(NSString *) name{
_name = name; } -(NSString *)name{
return _name; }
//ipod对象作为person类的listenMusic方法的形参 -(void) listenMusic:(iPod *) ipod{
//调用作为形参的 ipod 对象的playMusic方法 //iPod5播放歌曲————————————————— [ipod playMusic];
//I 对象作为 person 对象的局部变量 iPod *I = [iPod new];
//设置I对象的 名称 [I setName:@"iPod100"];
//调用作为局部变量的 I 对象的palyMusic方法 //iPod100播放歌曲————————————————— [I playMusic];
} @end main.m iPod * ipod = [iPod new]; [ipod setName:@"iPod5"]; Person *person = [Person new]; [person setName:@"小李"];
//调用person对象的listeMusic方法,参数是ipod对象 [person listenMusic:ipod];
|