iOS面试专题

分类Category & 扩展 Extension

2018-07-26  本文已影响0人  苏东没有坡

一:分类 Category

category别名分类,类别

简单来说,分类的作用就是为类添加方法。

apple的官方文档里,提到了category的2个使用场景< apple 官方文档 - Category>:

1. 拆分复杂类的实现

开发者可以根据功能拆分实现的文件,避免单个文件的臃肿,更易于代码管理。

屏幕快照 2018-07-26 下午4.17.48.png
2. 调用类的私有方法

一般来说,开发者在.m文件里声明一个私有方法,目的是不被外界所知,但是某种情况下我们又需要调用这个私有方法,这个时候就需要用到分类。
在分类中声明一个方法,方法名同私有方法,导入分类后,该类的实例就可以调用该私有方法。

/* Woman.h
*/
#import <Foundation/Foundation.h>
@interface Woman : NSObject
@end

/*Woman.m
*/
#import "Woman.h"

@interface Woman ()
- (void)getAge;
@end

@implementation Woman

- (void)getAge {
    NSLog(@"我20岁了");
}
/*Woman.h
*/
#import "Woman.h"

@interface Woman (info)
- (void)getAge;
@end

/* 调用私有方法getAge
*/
 Woman *woman = [[Woman alloc]init];
 [woman getAge];

// 不导入分类,报错"No visible @interface for 'Woman' declares the selector 'getAge'"
// 导入分类,输出"我20岁了"
    

除此之外,网上很多人提到了分类的另外两个使用场景:

1. 模拟多继承

首先需要明确的是,Object-C支持单继承而不支持多继承,通过category模拟多继承,实际上是通过runtime机制配合category去实现所谓的模拟。

场景:一个妹子既是歌手又是舞者
SingerDancerWoman 三个类,Woman继承了Singer类,可以sing,但是现在Woman也需要dance

/*Singer.h
*/
@interface Singer : NSObject
- (void)sing;
@end

/*Singer.m
*/
- (void)sing {
    NSLog(@"唱歌");
}

/*Dancer.h
*/
@interface Dancer : NSObject
- (void)dance;
@end

/*Dancer.m
*/
- (void)dance {
    NSLog(@"跳舞");
}

/*Woman.h
*/
@interface Woman : Singer
@end


// 无法调用dance
 Woman *woman = [[Woman alloc]init];
 [woman dance];

// 报错 No visible @interface for 'Woman' declares the selector 'dance'

为了让 woman可以顺利调用dance,可以创建一个"Singer+DanceMothod"分类去添加这个方法,导入分类后woman就可以调用dance而不报错了。

/*Singer+DanceMothod.h
*/
@interface Singer (DanceMothod)
- (void)dance;
@end

/*Singer+DanceMothod.m
*/
@implementation Singer (DanceMothod)
@end

虽然在分类里面添加了这个方法,但是并没有dance方法的实现,所以编译时不会报错,运行时仍然会报doesNotRecognizeSelector错误。为了模拟多继承,并不可以在分类中添加dance的实现,而需要调用Dancer类中的dance方法

系统在抛出doesNotRecognizeSelector异常之前,OC的消息转发机制为应用提供了3次拯救自己的机会,即
1.动态方法解析:resolveInstanceMethod
2.快速消息转发:forwardingTargetForSelector
3.标准消息转发:forwardInvocation
快速消息转发 就是检查类中是否实现了forwardingTargetForSelector方法。实现了则执行,如果返回值非nil或者非self,则向该返回值对象重新发送消息。

/* Woman.m
*/
- (id)forwardingTargetForSelector:(SEL)aSelector {
    Dancer *dancer = [[Dancer alloc] init];
    if ([dancer respondsToSelector:aSelector]) {
        return dancer;
    } else {
        return nil;
    }
}

// 调用dance
Woman *woman = [[Woman alloc]init];
[woman dance];
    
// 输出 "跳舞"
// 成功调用Dance类的dance方法,实现了多继承的模拟

2. 将framework的私有方法公开

我的理解就是apple提到的调用类的私有方法,不知为何把这个场景单独提出来。目前这个场景已经废了,苹果审核不允许开发者调用他们的私有方法。

二. 类扩展 Extension

事实上类扩展分类更加常用,就是我们在.m文件中的interface部分,我们一般在这里添加类的私有属性和方法。类扩展在编译期决议,随着类的产生而产生,也随着类的销毁而销毁。

@interface Singer()
// 这里是类私有属性,方法的声明
@end

三.分类Category 和扩展Extension的区别

Category:可以为类添加方法,不能添加成员变量,因为 category在运行期决议,在运行期对象的内存布局已经确定,如果添加实例对象会破坏类的内存布局,更详细的原因会在下面讲到。
Extension:可以添加方法,也可以添加成员变量,Extension在编译期决议,它实际上就是类的一部分。

四. 刨根究底 Category

category 的底层是结构体,具体的代码可以在runtime源码中的<objc-runtime-new.h>文件中找到,下载源码 点击这里 。下面的代码摘自runtime源码objc4-723版本

struct category_t {
    const char *name;  // 类名
    classref_t cls;  // 类
    struct method_list_t *instanceMethods;  // 实例方法列表
    struct method_list_t *classMethods;  // 类方法列表
    struct protocol_list_t *protocols;  // 协议列表
    struct property_list_t *instanceProperties; // 属性列表
    // Fields below this point are not always present on disk.
    struct property_list_t *_classProperties;
    // 如果是元类,就返回类方法列表;否则返回实例方法列表
    method_list_t *methodsForMeta(bool isMeta) {
        if (isMeta) return classMethods;
        else return instanceMethods;
    }

    property_list_t *propertiesForMeta(bool isMeta, struct header_info *hi);
};

从上面结构体的构成中可以看出,category可以添加实例方法类方法协议属性,但是无法添加成员变量

注意,属性成员变量并不是一个概念,属性可以被外部访问,通过点语法调用,编译器会自动生成gettersetter方法以及对应的成员变量成员变量只能在本类使用,通过_成员变量名调用。

category 虽然可以添加 属性,但和一般类中的属性不一样的是,它只会生成对应的getter,setter方法的声明,并不会生成getter,setter方法的实现与对应的成员变量。因此调用分类属性的时候会发现找不到getter,setter方法。

我们可以通过runtime中的关联对象给分类属性添加gettersetter方法

- (void)setDanceName:(NSString *)danceName {
    objc_setAssociatedObject(self, @selector(danceName), danceName, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (NSString *)danceName {
    return objc_getAssociatedObject(self, @selector(danceName));
}

有关关联对象,推荐阅读Draveness 关联对象 AssociatedObject 完全解析
有关Category更深层的理解,推荐阅读美团技术组深入理解Objective-C:Category

上一篇 下一篇

猜你喜欢

热点阅读