I have built a category for NSDate and I would like to encapsulate an attribute in this category to hold some data. But I can't achieve adding this attribute, only methods.
Is there any way to achieve this ?
Thank you.
Here some Code:
Filename: NSObject+dictionary.h
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
@interface NSObject (dictionary)
- (NSMutableDictionary*) getDictionary;
@end
Filename: 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");
}
Now every instance (of every class) has a dictionary, where you can store your custom attributes. With Key-Value Coding you can set a value like this:
[myObject setValue:attributeValue forKeyPath:@"dictionary.attributeName"]
And you can get the value like this:
[myObject valueForKeyPath:@"dictionary.attributeName"]
That even works great with the Interface Builder and User Defined Runtime Attributes.
Key Path Type Value
dictionary.attributeName String(or other Type) attributeValue
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With