在类的定义之外为类增加额外的存储空间
创建关联
列表7-1 把一个字符串关联到一个数组
- static
char overviewKey; - NSArray
* array =[[NSArray alloc] initWidthObjects:@"One", @"Two", @"Three", nil]; - //为了演示的目的,这里使用initWithFormat:来确保字符串可以被销毁
- NSString
* overview = [[NSString alloc] initWithFormat:@"@",@"First three numbers"]; - objc_setAssociatedObject(array,
&overviewKey, overview, OBJC_ASSOCIATION_RETAIN); -
- [overview
release]; - //(1)
overview仍然是可用的 -
- [array
release]; - //(2)overview
不可用
获取相关联的对象
- NSString
* associatedObject = (NSString *)objc_getAssociatedObject(array, &oveviewKey);
断开关联
- objc_setAssociatedObject(array,
&overviewKey, nil, OBJC_ASSOCIATION_ASSIGN);
一个完整的实例程序
- #import
- #import
-
-
- int
main(int argc, const char* argv[]) - {
-
NSAutoreleasePool * pool = [[NSAutoreleasePool] alloc init]; -
-
static char overviewKey; -
NSArray *array =[[NSArray alloc] initWidthObjects:@"One", @"Two", @"Three", nil]; -
//为了演示的目的,这里使用initWithFormat:来确保字符串可以被销毁 -
NSString * overview = [[NSString alloc] initWithFormat:@"@",@"First three numbers"]; -
objc_setAssociatedObject(array, &overviewKey, overview, OBJC_ASSOCIATION_RETAIN); -
[overview release]; -
-
NSString *associatedObject = (NSString *)objc_getAssociatedObject(arrray, &overviewKey); -
NSLog(@"associatedObject:%@", associatedObject); -
-
objc_setAssociatedObject(array, &overviewKey, nil, OBJC_ASSOCIATION_ASSIGN); -
[array release]; -
-
[pool drain]; -
return 0; - }