Oliver
Oliver

Reputation: 23510

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.

Upvotes: 4

Views: 2767

Answers (4)

Ossir
Ossir

Reputation: 3145

If you want to add attribute to class, you can try to use github.com/libObjCAttr. It's really easy to use, add it via pods, and then you can add attribute like that:

RF_ATTRIBUTE(YourAttributeClass, property1 = value1)
@interface NSDate (AttributedCategory)
@end

And in the code:

YourAttributeClass *attribute = [NSDate RF_attributeForClassWithAttributeType:[YourAttributeClass class]];
// Do whatever you want with attribute
NSLog(@"%@", attribute.property1)

Upvotes: 0

Przemyslaw
Przemyslaw

Reputation: 186

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

Upvotes: 12

Chris Hanson
Chris Hanson

Reputation: 55116

You can't add instance variables in categories.

However, you can add storage for your attribute to an object using associative references. Note that if you need to add more than one attribute, rather than adding an associative reference for each, you're probably better off adding a single reference to (say) an NSMutableDictionary, CFMutableDictionaryRef, or NSMapTable and using that for all of your attributes.

Upvotes: 4

Related Questions