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  沙加  阅读(379)  评论(0编辑  收藏  举报

导航