iOS小知识点02

iOS分类(Category)

Category的作用:为没有源代码的类添加方法。
使用Category需要注意的点:

(1). Category的方法不一定要在@implementation中实现,可以在其他地方实现,但当调用Category方法时,依据继承树,如果没有找到该方法的实现,在程序运行时会崩溃。
(2). Category理论上不能添加实例变量, 但可以通过runtime来添加.

给分类添加属性的例子

定义一个类ClassName
ClassName.h文件

#import 
@interface ClassName: NSObject
@end

ClassName.m文件

#import "ClassName.h"
@implementation ClassName
@end

创建一个ClassName的分类CategoryName
ClassName+CategoryName.h文件

#import "ClassName.h"
@interface ClassName (CategoryName)
// 给分类添加属性
@property (nonatomic, strong) NSString *str;
// 给分类添加方法
- (void)show;
@end

ClassName+CategoryName.m文件

#import "ClassName+CategoryName.h"
#Import 
static NSString *strKey = @"strKey";//定义一个静态变量strKey用来标记str属性
@implementation ClassName (CategoryName)
- (void)show {
    NSLog(@"the method %s is belong to %@", __func__, [self class]);
}
 // 通过运行时建立关联引用,可以给分类添加属性
/**
 * Sets an associated value for a given object using a given key and association policy.
 *
 * @param object The source object for the association.源对象
 * @param key The key for the association. 关联时用来标记是属于哪一个属性的key
 * @param value The value to associate with the key key for object. Pass nil to clear an existing association. 关联的对象
 * @param policy The policy for the association. For possible values, see “Associative Object Behaviors.” 关联策略
 *
 * @see objc_setAssociatedObject
 * @see objc_removeAssociatedObjects
 */

- (void)setStr:(NSString *)str {
objc_setAssociatedObject(self, &strKey, str, OBJC_ASSOCIATION_COPY);
}

/**
 * Returns the value associated with a given object for a given key.
 *
 * @param object The source object for the association. 源对象
 * @param key The key for the association. 关联时用来标记是属于哪一个属性的key
 *
 * @return The value associated with the key \e key for \e object.
 *
 * @see objc_setAssociatedObject
 */
- (NSString *)str {
    return objc_getAssociatedObject(self, &strKey);
}

- (NSString *)description {
    return [NSString stringWithFormat:@"class:%p, str:%@", self, self.str];
}
@end

在ViewDidLoad中

- (void)viewDidLoad {
    [super viewDidLoad];
    ClassName *test1 = [[ClassName alloc] init];
    test1.str = @"123";
    NSLog(@"%@",test1);
    [test1 show];
}

输出结果为:

 Category_Extension[2107:111478] class:0x7fd8f0c151e0, str:123
 Category_Extension[2107:111478] the method -[ClassName(CategoryName) show] is belong to ClassName

属性str已经成功关联到分类中。

你可能感兴趣的:(iOS小知识点02)