【什么时候使用分类 Objective-C语言】

前言

什么时候使用分类
当1个类的方法很多很杂的时候,当1个类很臃肿的时候,
那么这个时候我们就可以使用分类,将这个类分为多个模块,将功能相似的方法写在同1个模块之中

一、例如,有一个学生类:类中有很多个方法:1.吃、喝、拉、撒、睡;2.学习、敲代码、写书;3.玩Dota、玩LOL、玩CF;4.爬山、跑步、踢足球。。。

1.学生类的方法虽然很多,但是可以分成几个大类:

1.吃、喝、拉、撒、睡。。。基本行为
2.学习、敲代码、写书。。。学习
3.玩Dota、玩LOL、玩CF。。。玩
4.爬山、跑步、踢足球。。。运动2:19

2.于是,我们就可以为学生类写4个分类:

1.基本行为:写在1个分类

2.学习:写在1个分类

3.玩:写在1个分类

4.运动:写在1个分类

3.例如:先写1个本类:Student

#import <Foundation/Foundation.h>
@interface Student:NSObject
@property(nonatomic,strong)NSString *name;
@property(nonatomic,assign)int age;
@property(nonatomic,strong)NSString *stuNumber;
@end

#import “Student.h”
@implementation Student

@end

4.再为Student写1个分类:basic,把吃、喝、拉、撒、睡写在这个分类中

#import “Student.h”
@interface Student (basic)
– (void)eat;
– (void)drink;
– (void)la;
– (void)sa;
– (void)sleep;
@end
#import “Student+basic.h”
@implementation Student (basic)
– (void)eat{}
– (void)drink{}
– (void)la{}
– (void)sa{}
– (void)sleep{}
@end

5.在为Student写1个分类:play,把玩Dota、玩LOL,玩CF写在这个分类里

#import “Student.h”
@interface Student (play)
– (void)playDota;
– (void)playLOL;
– (void)playCF;
@end
#import “Student+play.h”
@implementation Student (play)

  • (void)playDota{}
  • (void)playLOL{}
  • (void)playCF{}
    @end

6.总结,如果1个类的方法很多很杂的时候,可以把相似功能的方法,写在1个分类中。

猜你喜欢

转载自blog.csdn.net/madoca/article/details/126602070
今日推荐