在Objective-C中复合是通过包含作为实例变量的对象指针实现的
严格来说,只有对象间的组合才叫复合
--------------------Car.h---------------------------
#import <Foundation/Foundation.h>
#import "Wheel.h"
@interface Car : NSObject
@property Wheel *wheel1;
@property Wheel *wheel2;
@property Wheel *wheel3;
@property Wheel *wheel4;
/*
1.如果复合的属性是另外一个类的类型,那么在使用之前记得初始化该属性
2.如果想要在[内部没有初始化复合属性]的前提下使用的话,需要传入的参数必须是已经初始化过的
*/
@end
-------------------Car.m-------------------------
#import "Car.h"
@implementation Car
//内部初始化复合属性
- (instancetype)init
{
self = [super init];
if (self) {
self.wheel1 = [[Wheel alloc] init];
self.wheel2 = [[Wheel alloc] init];
self.wheel3 = [[Wheel alloc] init];
self.wheel4 = [[Wheel alloc] init];
}
return self;
}
- (NSString *)description
{
return [NSString stringWithFormat:@"\nwheel1.type:%@ \nwheel2.type:%@ \nwheel3.type:%@ \nwheel4.type:%@", self.wheel1.type, self.wheel2.type, self.wheel3.type, self.wheel4.type];
}
@end
---------------------Wheel------------------------
#import <Foundation/Foundation.h>
@interface Wheel : NSObject
@property NSString *type;
@end
#import "Wheel.h"
@implementation Wheel
@end
--------------------测试文件--------------------------
#import <Foundation/Foundation.h>
#import "Wheel.h"
#import "Car.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Car *car = [[Car alloc] init];
// 外部初始化复合属性
// Wheel *wheel1 = [[Wheel alloc] init];
// wheel1.type = @"法拉利的轮子1";
// Wheel *wheel2 = [[Wheel alloc] init];
// wheel2.type = @"法拉利的轮子2";
// Wheel *wheel3 = [[Wheel alloc] init];
// wheel3.type = @"法拉利的轮子3";
// Wheel *wheel4 = [[Wheel alloc] init];
// wheel4.type = @"法拉利的轮子4";
//
// car.wheel1 = wheel1;
// car.wheel2 = wheel2;
// car.wheel3 = wheel3;
// car.wheel4 = wheel4;
car.wheel1.type=@"宝马的轮子1";
car.wheel2.type=@"宝马的轮子2";
car.wheel3.type=@"宝马的轮子3";
car.wheel4.type=@"宝马的轮子4";
NSLog(@"%@",car);
}
return 0;
}