Objective-C:向类别添加属性

Oli*_*ver 4 attributes objective-c categories

我已经为NSDate构建了一个类别,我想在这个类别中封装一个属性来保存一些数据.但我无法实现添加此属性,只能添加方法.

有没有办法实现这个目标?

谢谢.

小智 12

这里有一些代码:

文件名:NSObject + dictionary.h

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

文件名: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");
}
Run Code Online (Sandbox Code Playgroud)

现在每个实例(每个类)都有一个字典,您可以在其中存储自定义属性.使用键值编码,您可以设置如下值:

[myObject setValue:attributeValue forKeyPath:@"dictionary.attributeName"]
Run Code Online (Sandbox Code Playgroud)

你可以得到这样的价值:

[myObject valueForKeyPath:@"dictionary.attributeName"]
Run Code Online (Sandbox Code Playgroud)

这甚至适用于Interface Builder和用户定义的运行时属性.

Key Path                   Type                     Value
dictionary.attributeName   String(or other Type)    attributeValue
Run Code Online (Sandbox Code Playgroud)