这里有一些代码:
文件名:NSObject+dictionary.h
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
@interface NSObject (dictionary)
- (NSMutableDictionary*) getDictionary;
@end
文件名:NSObject+dictionary.m
#import "NSObject+dictionary.h"
@implementation NSObject (dictionary)
- (NSMutableDictionary*) getDictionary
{
if (objc_getAssociatedObject(self, @"dictionary")==nil)
{
objc_setAssociatedObject(self,@"dictionary",[[NSMutableDictionary alloc] init],OBJC_ASSOCIATION_RETAIN);
}
return (NSMutableDictionary *)objc_getAssociatedObject(self, @"dictionary");
}
现在(每个类的)每个实例都有一个字典,您可以在其中存储自定义属性。
和键值编码 http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/KeyValueCoding/Articles/KeyValueCoding.html你可以设置这样的值:
[myObject setValue:attributeValue forKeyPath:@"dictionary.attributeName"]
你可以得到这样的值:
[myObject valueForKeyPath:@"dictionary.attributeName"]
这甚至可以与 Interface Builder 和用户定义的运行时属性配合使用。
Key Path Type Value
dictionary.attributeName String(or other Type) attributeValue