一、分类
1.1 分类简介
• 分类只能增加方法, 不能增加成员变量、@property(可能编译不报错,但是运行有问题)
• 分类可以访问原来类中的成员变量
• 如果分类和原来类出现同名的方法, 优先调用分类中的方法, 原来类中的方法会被忽略
• 方法调用的优先级(从高到低)
➢ 分类(最后参与编译的分类优先),只要有分类就优先调用分类,不考虑与主类的编译顺序。
➢ 原来类
➢ 父类
Person+PlayGame分类和Person+Study分类以及Person原来类都分别实现了run方法。
这张图展示分类调用顺序。
即使原来类的编译顺序是最后一个,调用Person run方法依旧调用分类中相对顺序在最后编译的分类的run方法。
1.2 示例代码
Person.h
#import <Foundation/Foundation.h>
@interface Person : NSObject
- (void)run;
@end
Person.m
#import "Person.h"
@implementation Person
- (void)run{
NSLog(@"本类run。。。");
}
@end
Person+PlayGame.h
#import "Person.h"
@interface Person (PlayGame)
- (void)playLol;
- (void)run;
@end
Person+PlayGame.m
#import "Person+PlayGame.h"
@implementation Person (PlayGame)
- (void)playLol{
NSLog(@"此人在玩游戏。。。");
}
- (void)run{
NSLog(@"playgame run...");
}
@end
Person+Study.h
#import "Person.h"
@interface Person (Study)
- (void)study;
- (void)run;
@end
Person+Study.m
#import "Person+Study.h"
@implementation Person (Study)
- (void)study{
NSLog(@"此人在学习。。。");
}
- (void)run{
NSLog(@"study run...");
}
@end
二、
2.1 类扩展(Extension)简介
类扩展是分类的一个特例。
Extension是Category的一个特例。
起名字为匿名,并且添加的方法一定要实现。(category可以不实现)。因此又叫匿名分类。可以为一个类添加额外的变量,方法或者合成属性。
我的理解:
延展就是为类一开始设计没有考虑到的情况增加新的属性方法来弥补。延展的实现如下:
2.2 示例代码
Person.h
#import <Foundation/Foundation.h>
@interface Person : NSObject
- (void)testRun;
@end
Person_work.h
#import "Person.h"
@interface Person ()
{
int _height;
}
- (void)run;
- (void)work;
@end
Person.m
#import "Person.h"
#import "Person_work.h"
@interface Person()
{
int _age;
}
- (void)run;
@end
@implementation Person
- (void)work{
NSLog(@"%d",_age);
NSLog(@"working。。。");
NSLog(@"height is :%d",_height);
}
- (void)run{
NSLog(@"running ....");
NSLog(@"%d",_age);
}
- (void)testRun{
[self run];
NSLog(@"height is :%d",_height);
}
@end
有以下方法实现类扩展:
1. 直接在Person.m文件中用 @interface Person()的方法,然后在类本身的@implementation中去实现扩展的方法;
2. 新建Objective-C文件work,选择Extension,扩展的原类为Person,然后生成Person_work.h头文件,在头文件中扩展属性和方法,同样需要在原类的.m文件中区实现。
Objective-C 分类与扩展详解
本文详细介绍了Objective-C中的分类(Category)与类扩展(Extension)的概念及其使用方法。包括分类如何增加方法而不添加成员变量,分类方法调用的优先级,以及如何通过类扩展为类添加额外的变量和方法。
8895

被折叠的 条评论
为什么被折叠?



