关联关系 当 B 对象作为 A 对象的成员变量时,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;
//iPod对象作为 Person的成员变量 iPod *_ipod; }
//封装_name成员变量 -(void)setName:(NSString *) name; -(NSString *)name;
//封装_iPod成员变量 -(void)setIpod:(iPod *) ipod; -(iPod *)ipod;
-(void) listenMusic; @end
Person.m @implementation Person -(void)setName:(NSString *) name{
_name = name; } -(NSString *)name{
return _name; }
//实现成员变量_ipod的封装 -(void)setIpod:(iPod *) ipod{
_ipod = ipod; } -(iPod *)ipod{
return _ipod; } -(void) listenMusic{ //调用成员变量 _ipod 的 playMusic方法 [_ipod playMusic]; } @end main.m iPod * ipod = [iPod new]; [ipod setName:@"iPod5"]; Person *person = [Person new]; [person setName:@"小李"];
//给person对象的ipod成员变量赋值 [person setIpod:ipod]; [person listenMusic];
|