Objective-C: add attribute to category

I created a category for NSDate, and I would like to encapsulate an attribute in this category to store some data. But I can not add this attribute, only methods.

Is there any way to achieve this?

Thanks.

+4
source share
4 answers

Here is some code:

File Name: NSObject + dictionary.h

#import <Foundation/Foundation.h> #import <objc/runtime.h> @interface NSObject (dictionary) - (NSMutableDictionary*) getDictionary; @end 

File Name: 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 each instance (of each class) has a dictionary in which you can save your custom attributes. Using keyword encoding , you can set this value:

 [myObject setValue:attributeValue forKeyPath:@"dictionary.attributeName"] 

And you can get the value as follows:

 [myObject valueForKeyPath:@"dictionary.attributeName"] 

This works great with the Builder interface and custom runtime attributes.

 Key Path Type Value dictionary.attributeName String(or other Type) attributeValue 
+12
source

You cannot add instance variables to categories.

However, you can add storage for your attribute to the object using associative links . Please note: if you need to add several attributes, instead of adding an associative link for each of them, you probably should add a separate link (say) to NSMutableDictionary, CFMutableDictionaryRef or NSMapTable and use it for all your attributes.

+4
source

If you want to add an attribute to a class, you can try using github.com/libObjCAttr . It is very easy to use, adds it via pods, and then you can add an attribute like this:

 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) 
0
source

Source: https://habr.com/ru/post/1334256/


All Articles