Category

作者: 红鲤鱼绿鲤鱼与鱼 | 来源:发表于2016-10-18 11:51 被阅读6次
  • 作用
    1.给已有类添加方法
    2.给已有类添加属性
    3.分离实现
    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的区别
    虽然他们语法上很接近,但是extension中是可以定义@property的,category中则不行。也就是说alloc + init的时候,编译器会将extension中的内容也考虑进来,该分配空间的分配空间。

相关文章

网友评论

      本文标题:Category

      本文链接:https://www.haomeiwen.com/subject/rtxtuttx.html