f(sixleaves) = sixleaves

重剑无锋 大巧不工

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  95 随笔 :: 0 文章 :: 7 评论 :: 0 Trackbacks
Person.h
 1 
 2 #import <Foundation/Foundation.h>
 3 
 4 @interface Person : NSObject
 5 {
 6     int _test;
 7 }
 8 @property int age;
 9 @property NSString * name;
10 
11 - (id)initWithName:(NSString *)name andAge:(int)age;
12 - (void)test;
13 @end
Person.m
 1 #import "Person.h"
 2 @implementation Person
 3 
 4 - (id)initWithName:(NSString *)name andAge:(int)age
 5 {
 6 
 7     if (self = [super init]) {
 8 
 9         _name = name;
10         _age = age;
11         
12     }
13     return self;
14 }
15 
16 - (void)test
17 {
18 
19     NSLog(@"Person-test");
20 }
21 @end
Person+Study.h
1 #import "Person.h" // 包含Person文件才能找到Person这个类,才能给其加分类。
2 
3 @interface Person (Study)
4 - (void)study;
5 
6 @end
Person+Study.m
 1 #import "Person+Study.h"
 2 
 3 @implementation Person (Study)
 4 - (void)study
 5 {
 6 
 7     NSLog(@"Person+Study, _test = %d", _test);
 8 }
 9 
10 - (void)test
11 {
12 
13     NSLog(@"Person (Study)-test");
14 }
15 @end
Person+JJ.h
1 #import "Person.h"
2 
3 
4 @interface Person (JJ)
5 
6 - (void)study2;
7 
8 @end
Person+JJ.m
 1 
 2 
 3 #import "Person+JJ.h"
 4 
 5 @implementation Person (JJ)
 6 
 7 - (void)study2
 8 {
 9 
10 
11 }
12 
13 - (void)test
14 {
15     NSLog(@"Person (jj)-test");
16 }
17 @end
分类.m
 1 
 2 #import <Foundation/Foundation.h>
 3 #import "Person.h"
 4 #import "Person+Study.h"
 5 #import "Person+JJ.h"
 6 int main() {
 7 
 8     Person *p = [[Person alloc] init];
 9     [p study];
10               // 有先分类中找 ==》 类中找 ==》 父类中找
11     [p test]; // 分类中扩充了原来的方法,会覆盖掉原来的方法。
12     return 0;
13 }
14 
15 /*
16 A.分类的作用:
         1.在不改变这个类的模型(文件内容)基础上,为这个类增加方法。
17      2.基于分类的作用,我们可以用分类来实现模块化开发。
18 B.分类的规范:
19     1.分类一般是以模块名命名。
20     2.分类的文件名是类名+文件名。
21 
22 C.分类(3个)注意事项:
23 
24     1 分类只能增加方法,不能加成员变量。但分类中的方法也能访问非私有的成员变量。
25     2 分类可以重新实现原来类中的方法,会覆盖掉这个方法。
26     3 方法调用的优先级 :
27          1.分类 》 原来类 》 父类
28          2.多个分类中增加相同的方法,最后一个编译的才有效
29 
30 
31 
32 Tips:
33 可以选中项目,在Build Phase =》 Compile Source中查看编译的顺序,并作出调整。
34 验证方法:
35 在终端分别输入编译链接命令,并运行程序验证
36 cc Person.m Person+Study.m Person+JJ.m 分类.m +-framework Foundation
37 ./a.out
38 
39 cc Person.m Person+JJ.m Person+Study.m 分类.m +-framework Foundation
40 ./a.out
41 */
posted on 2015-05-03 00:23 swp 阅读(90) 评论(0)  编辑 收藏 引用 所属分类: objective-c

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理