Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C : adding attribute to a category

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.

like image 587
Oliver Avatar asked Dec 03 '22 03:12

Oliver


1 Answers

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
like image 128
Przemyslaw Avatar answered Dec 23 '22 02:12

Przemyslaw