Objective-C的:添加属性类别 [英] Objective-C : adding attribute to a category

查看:194
本文介绍了Objective-C的:添加属性类别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经建立了一个的NSDate类,我想封装属性此类别中保存一些数据。但我不能达到增加该属性,只有方法。

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 ?

感谢您。

推荐答案

下面一些code:

文件名:NSObject的+ dictionary.h

Filename: NSObject+dictionary.h

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

文件名:NSObject的+ dictionary.m

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");
}

现在每个实例(每类),有一本​​字典,在那里你可以存储您的自定义属性。
随着<一个href=\"http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/KeyValueCoding/Articles/KeyValueCoding.html\">Key-Value编码你可以设置这样的值:

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

这篇关于Objective-C的:添加属性类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆