iOS分類(Category)
Category的作用:為沒有源代碼的類添加方法。
使用Category需要注意的點:
(1). Category的方法不一定要在@implementation中實現,可以在其他地方實現,但當調用Category方法時,依據繼承樹,如果沒有找到該方法的實現,在程序運行時會崩潰。
(2). Category理論上不能添加實例變量, 但可以通過runtime來添加.
給分類添加屬性的例子
定義一個類ClassName
ClassName.h文件
#import <Foundation/Foundation.h>
@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 <objc/runtime.h>
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已經成功關聯到分類中。