如何给category添加属性

阅读更多

主要是使用了runtime中的associative机制。

 

NSDate+extension.h

@interface NSDate (extension)

@property (nonatomic, strong) NSDateFormatter *formatter;

@end

 

NSDate+extension.m

#import "NSDate+extension.h"
#include 

static void *formatterKey = (void *) @"formatterKey";

@implementation NSDate (extension)
@dynamic formatter;

+ (NSDateFormatter *)formatter {
	return objc_getAssociatedObject(self, formatterKey);
}

+ (void)setFormatter:(NSDateFormatter *)formatterProperty {
	objc_setAssociatedObject(self, formatterKey, formatterProperty, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end

 

你可能感兴趣的:(iPhone,iOS,runtime,category)