Objective-C 学习笔记 - part 7 - 相关引用

上一章讲了对类的方法进行扩展, 相关引用就是为现存的 class 增加另外的实例可引用变量(通常是一个静态变量),这个功能只在 iOS and OS X v10.6 以后提供。

引入这种机制的原因类同于类的方法扩展。

static char overviewKey;
 
NSArray *array =
    [[NSArray alloc] initWithObjects:@"One", @"Two", @"Three", nil];
// For the purposes of illustration, use initWithFormat: to ensure
// the string can be deallocated
NSString *overview =
    [[NSString alloc] initWithFormat:@"%@", @"First three numbers"];
 
objc_setAssociatedObject (
    array,
    &overviewKey,
    overview,
    OBJC_ASSOCIATION_RETAIN
);
 
[overview release];
// (1) overview valid
[array release];
// (2) overview invalid

如何获取值:
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
 
int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
 
    static char overviewKey;
 
    NSArray *array = [[NSArray alloc]
        initWithObjects:@ "One", @"Two", @"Three", nil];
    // For the purposes of illustration, use initWithFormat: to ensure
    // we get a deallocatable string
    NSString *overview = [[NSString alloc]
        initWithFormat:@"%@", @"First three numbers"];
 
    objc_setAssociatedObject (
        array,
        &overviewKey,
        overview,
        OBJC_ASSOCIATION_RETAIN
    );
    [overview release];
 
    NSString *associatedObject =
        (NSString *) objc_getAssociatedObject (array, &overviewKey);
    NSLog(@"associatedObject: %@", associatedObject);
 
    objc_setAssociatedObject (
        array,
        &overviewKey,
        nil,
        OBJC_ASSOCIATION_ASSIGN
    );
    [array release];
 
    [pool drain];
    return 0;
}

posted on 2011-08-17 15:08 沙加 阅读(63) 评论(0) 编辑 收藏

导航

公告

昵称:沙加
园龄:5年11个月
粉丝:36
关注:13
<2011年8月>
31123456
78910111213
14151617181920
21222324252627
28293031123
45678910

统计

搜索

 

我的标签

随笔分类(89)

随笔档案(98)

Atlas相关

积分与排名

最新评论

阅读排行榜

推荐排行榜