标签:
正所谓复合,便是定义的这个类中的成员是另外类的实例方法。
也就是把其他对象作为自身的题部分,以提升自身的功能,
就相当于C语言中的函数嵌套。下面是一段代码(多个文件放在一块了):
1 /***Computer类的声明***Computer类的声明***Computer类的声明***/
2 #import <Foundation/Foundation.h>
3
4 @interface Computer : NSObject
5
6 @property (nonatomic, strong) NSString *brand;//声明一个字符串对象属性brand
7
8 @end
9
10 /***Computer类的实现***Computer类的实现***Computer类的实现***/
11 #import "Computer.h"
12
13 @implementation Computer
14
15 @end
16
17 /***Desk类的声明***Desk类的声明***Desk类的声明***/
18
19 #import <Foundation/Foundation.h>
20
21 @interface Desk : NSObject
22
23 @property (nonatomic, strong) NSString *color;//声明一个字符串对象属性color
24
25 @end
26
27 /***Desk类的实现***Desk类的实现***Desk类的实现***/
28
29 #import "Desk.h"
30
31 @implementation Desk
32
33 @end
34
35 /***ClassRoom类的声明***ClassRoom类的声明***ClassRoom类的声明***/
36
37 #import <Foundation/Foundation.h>
38 #import "Desk.h"
39 #import "Computer.h"
40
41 @interface ClassRoom : NSObject
42 @property (nonatomic, strong) Desk *desk;//声明一个Desk的对象desk的属性 这里用的就是复合
43 @property (nonatomic, strong) Computer *computer;////声明一个Computer的对象computer的属性这里用的也是复合
44 @end
45
46 /***ClassRoom类的实现***ClassRoom类的实现***ClassRoom类的实现***/
47
48 #import "ClassRoom.h"
49 @implementation ClassRoom
50 -(NSString *)description{ //库方法,方法的重写
51 NSString *str = [NSString stringWithFormat/*方法*/:@"我们的教室有%@的桌子,%@电脑",self/*当前方法的调用者-ClassRoom*/.desk.color,self.computer.brand];
52 return str;
53 }
54 @end
55
56 /***主函数***主函数***主函数***主函数***主函数***主函数***主函数*/
57
58 #import <Foundation/Foundation.h>
59 #import "ClassRoom.h"
60
61 int main(int argc, const char * argv[]) {
62 @autoreleasepool {
63
64 ClassRoom *classRoom = [[ClassRoom alloc] init];
65 Desk *de= [[Desk alloc] init];
66 classRoom.desk = de;//给对象的属性(类的对象)赋值,先初始化该属性
67 classRoom.desk.color = @"褐色";//给属性的属性赋值
68
69 Computer *com = [[Computer alloc] init];
70 com.brand = @"黑苹果";//对象完全初始化之后,再给其所属的对象赋值
71 classRoom.computer = com;
72
73 NSLog(@"%@",classRoom);
74 }
75 return 0;
76 }
标签:
原文地址:http://www.cnblogs.com/liuguan/p/4906499.html