正所谓复合,便是定义的这个类中的成员是另外类的实例方法。
也就是把其他对象作为自身的题部分,以提升自身的功能,
就相当于C语言中的函数嵌套。下面是一段代码(多个文件放在一块了):
/***Computer类的声明***Computer类的声明***Computer类的声明***/
#import <Foundation/Foundation.h> @interface Computer : NSObject @property (nonatomic, strong) NSString *brand;//声明一个字符串对象属性brand @end /***Computer类的实现***Computer类的实现***Computer类的实现***/
#import "Computer.h" @implementation Computer @end /***Desk类的声明***Desk类的声明***Desk类的声明***/ #import <Foundation/Foundation.h> @interface Desk : NSObject @property (nonatomic, strong) NSString *color;//声明一个字符串对象属性color @end /***Desk类的实现***Desk类的实现***Desk类的实现***/ #import "Desk.h" @implementation Desk @end /***ClassRoom类的声明***ClassRoom类的声明***ClassRoom类的声明***/ #import <Foundation/Foundation.h>
#import "Desk.h"
#import "Computer.h" @interface ClassRoom : NSObject
@property (nonatomic, strong) Desk *desk;//声明一个Desk的对象desk的属性 这里用的就是复合
@property (nonatomic, strong) Computer *computer;////声明一个Computer的对象computer的属性这里用的也是复合
@end /***ClassRoom类的实现***ClassRoom类的实现***ClassRoom类的实现***/ #import "ClassRoom.h"
@implementation ClassRoom
-(NSString *)description{ //库方法,方法的重写
NSString *str = [NSString stringWithFormat/*方法*/:@"我们的教室有%@的桌子,%@电脑",self/*当前方法的调用者-ClassRoom*/.desk.color,self.computer.brand];
return str;
}
@end /***主函数***主函数***主函数***主函数***主函数***主函数***主函数*/ #import <Foundation/Foundation.h>
#import "ClassRoom.h" int main(int argc, const char * argv[]) {
@autoreleasepool { ClassRoom *classRoom = [[ClassRoom alloc] init];
Desk *de= [[Desk alloc] init];
classRoom.desk = de;//给对象的属性(类的对象)赋值,先初始化该属性
classRoom.desk.color = @"褐色";//给属性的属性赋值 Computer *com = [[Computer alloc] init];
com.brand = @"黑苹果";//对象完全初始化之后,再给其所属的对象赋值
classRoom.computer = com; NSLog(@"%@",classRoom);
}
return 0;
}
另一个例子:
#import <Foundation/Foundation.h>
//门类
@interface Door:NSObject
-(void)open;
-(void)close;
@property(nonatomic,strong)NSString *replace; //实现更换门
@end
@implementation Door
-(void)open
{
NSLog(@"开门");
}
-(void)close
{
NSLog(@"关门");
}
-(void)color
{
NSLog(@"门得颜色%@",self.replace);
}
@end //窗户类
@interface Window:Door
@end
@implementation Window
-(void)open
{
NSLog(@"开窗");
}
-(void)close
{
NSLog(@"关窗");
}
@end
//房屋类
@interface Housing:NSObject
//{
// Door *door;//门
// Window *window;//窗户
//}
@property(nonatomic)Door *door;//门
@property(nonatomic)Window *window;//窗户
-(void)InAndOut;//进出方法
-(void)takeAbreath;//换气方法
@end
@implementation Housing
-(void)InAndOut
{
// door = [[Door alloc] init];
NSLog(@"进屋");
[_door open];
NSLog(@"出屋");
[_door close];
}//进出方法
-(void)takeAbreath
{
// window = [[Window alloc] init ];
[_window open];
NSLog(@"进气");
NSLog(@"出气");
[_window close];
}//换气方法 @end
int main(int argc, const char * argv[])
{
@autoreleasepool
{
Housing *housing = [[Housing alloc] init]; housing .door = [[Door alloc] init];
housing .window = [[Window alloc] init ];
[housing InAndOut];
[housing takeAbreath];
housing.door.replace = @"红色";
[housing.door color];
}
return ;
}