iOS分類(Category)
Category的作用:為沒(méi)有源代碼的類添加方法。
使用Category需要注意的點(diǎn):
(1). Category的方法不一定要在@implementation中實(shí)現(xiàn),可以在其他地方實(shí)現(xiàn),但當(dāng)調(diào)用Category方法時(shí),依據(jù)繼承樹(shù),如果沒(méi)有找到該方法的實(shí)現(xiàn),在程序運(yùn)行時(shí)會(huì)崩潰。
(2). Category理論上不能添加實(shí)例變量, 但可以通過(guò)runtime來(lái)添加.
給分類添加屬性的例子
定義一個(gè)類ClassName
ClassName.h文件
#import <Foundation/Foundation.h>
@interface ClassName: NSObject
@end
ClassName.m文件
#import "ClassName.h"
@implementation ClassName
@end
創(chuàng)建一個(gè)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 <objc/runtime.h>
static NSString *strKey = @"strKey";//定義一個(gè)靜態(tài)變量strKey用來(lái)標(biāo)記str屬性
@implementation ClassName (CategoryName)
- (void)show {
NSLog(@"the method %s is belong to %@", __func__, [self class]);
}
// 通過(guò)運(yùn)行時(shí)建立關(guān)聯(lián)引用,可以給分類添加屬性
/**
* Sets an associated value for a given object using a given key and association policy.
*
* @param object The source object for the association.源對(duì)象
* @param key The key for the association. 關(guān)聯(lián)時(shí)用來(lái)標(biāo)記是屬于哪一個(gè)屬性的key
* @param value The value to associate with the key key for object. Pass nil to clear an existing association. 關(guān)聯(lián)的對(duì)象
* @param policy The policy for the association. For possible values, see “Associative Object Behaviors.” 關(guān)聯(lián)策略
*
* @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. 源對(duì)象
* @param key The key for the association. 關(guān)聯(lián)時(shí)用來(lái)標(biāo)記是屬于哪一個(gè)屬性的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];
}
輸出結(jié)果為:
Category_Extension[2107:111478] class:0x7fd8f0c151e0, str:123
Category_Extension[2107:111478] the method -[ClassName(CategoryName) show] is belong to ClassName
屬性str已經(jīng)成功關(guān)聯(lián)到分類中。