如何给category添加属性

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

NSDate+extension.h

@interface NSDate (extension)

@property (nonatomic, strong) NSDateFormatter *formatter;

@end

NSDate+extension.m

#import "NSDate+extension.h"
#include <objc/runtime.h>

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

猜你喜欢

转载自eric-gao.iteye.com/blog/2234055