Objective-C : adding attribute to a category

强颜欢笑 提交于 2019-12-03 17:24:32
Przemyslaw

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
Chris Hanson

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.

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!