- 作用
1.給已有類添加方法
2.給已有類添加屬性
3.分離實(shí)現(xiàn)
4.隱藏基類接口
NSString+SafeFormat.h文件
#import <Foundation/Foundation.h>
@interface NSString (SafeFormat)
@property (nonatomic, copy) NSString *name;//添加屬性
- (NSNumber *)safeIntegerNumber;//添加方法
@end
NSString+SafeFormat.m文件
#import "NSString+SafeFormat.h"
static NSMutableDictionary *KName;
@implementation NSString (SafeFormat)
- (void)initKName {
if (KName == nil) {
KName = [NSMutableDictionary dictionary];
}
}
- (NSString *)name {
[self initKName];
return KName[@((NSInteger)self)];
}
- (void)setName:(NSString *)name {
[self initKName];
KName[@((NSInteger)self)] = name;
}
- (NSNumber *)safeIntegerNumber {
return @([self integerValue]);
}
@end
- 與extension的區(qū)別
雖然他們語(yǔ)法上很接近,但是extension中是可以定義@property的反璃,category中則不行昵慌。也就是說(shuō)alloc + init的時(shí)候,編譯器會(huì)將extension中的內(nèi)容也考慮進(jìn)來(lái)淮蜈,該分配空間的分配空間斋攀。