在object-c中我们知道可以使用categories来为扩展类方法(比如我们可以为系统的类添加自己的方法)
例如:我们要想在每个NSString前面添加一个
@interface NSString ( CategoryName ) |
// method declarations - (NSString *) getNSString; |
@end |
@implementation NSString ( CategoryName ) |
// method definitions - (NSString *)getNSString { return [NSString stringWithFormat:@"hello+%@", self]; } |
@end |
调用方法如下:
NSString *str = @"world";
NSLog(@"str == [%@]", [str getNSString]);
打印出来的结果:str == [hello+world]
我们知道Categories可以为类扩展自己的方法,但是如何添加属性呢?
例如我们如何为NSString添加一个tag的属性(我们可以用Associative)
********************************************************************
Associative references are available only in iOS and in Mac OS X v10.6 and later
********************************************************************
#import <objc/runtime.h>
@interface NSString(categories)
@property(nonatomic,retain) id objectTag;
- (NSString *)getNSString;
@end
static const char *ObjectTagKey = "ObjectTag";
@implementation NSString(categories)
@dynamic objectTag;
- (id)objectTag {
return objc_getAssociatedObject(self, ObjectTagKey);
}
- (void)setObjectTag:(id)newObjectTag {
objc_setAssociatedObject(self, ObjectTagKey, newObjectTag, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (NSString *)getNSString
{
return [NSString stringWithFormat:@"%@+hello", self];
}
@end
NSString *str = @"world";
NSLog(@"str == [%@]", [str getNSString]);
str.objectTag = [NSNumber numberWithInt:7];//对objectTag设置NSMunber类型的值
NSLog(@"str.objectTag===[%@],object class === [%@]", str.objectTag, [str.objectTag class]);
str.objectTag = @"5";//对objectTag设置NSString类型的值
NSLog(@"str.objectTag===[%@],object class === [%@]", str.objectTag, [str.objectTag class]);
str.objectTag = nil;//对objectTag设置为nil,当然我们也可以用objc_removeAssociatedObjects
NSLog(@"str.objectTag===[%@],object class === [%@]", str.objectTag, [str.objectTag class]);
打印结果如图
详见官方文档
http://developer.apple.com/library/mac/#documentation/cocoa/conceptual/ObjectiveC/Chapters/ocAssociativeReferences.html%23//apple_ref/doc/uid/TP30001163-CH24-SW1