惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

C
Check Point Blog
Microsoft Security Blog
Microsoft Security Blog
aimingoo的专栏
aimingoo的专栏
V
V2EX
博客园 - 【当耐特】
T
Tailwind CSS Blog
Apple Machine Learning Research
Apple Machine Learning Research
量子位
MyScale Blog
MyScale Blog
Hugging Face - Blog
Hugging Face - Blog
大猫的无限游戏
大猫的无限游戏
The Cloudflare Blog
月光博客
月光博客
I
InfoQ
WordPress大学
WordPress大学
Martin Fowler
Martin Fowler
T
The Blog of Author Tim Ferriss
爱范儿
爱范儿
小众软件
小众软件
罗磊的独立博客
Recent Announcements
Recent Announcements
Blog — PlanetScale
Blog — PlanetScale
J
Java Code Geeks
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC

博客园 - 沙加

前端设计模式之 MPVC Part 3 前端设计模式之 MPVC Part 2 前端设计模式之 MPVC Part 1 App Engine 缓存与数据一致性 常用跨浏览器效果 同步请求真的有那么恐怖? Google Closure 的单元测试纪要 双飞翼布局的选区问题 一个 JS 面试题目 HTML 5 之旅 part 1 - 无头苍蝇 bind, delegate, live 三者的区别 Objective-C 学习笔记 - part 12 - 多线程 Objective-C 学习笔记 - part 11 - 错误处理 Objective-C 学习笔记 - part 10 - 选择器 Objective-C 学习笔记 - part 9 - 静态标记的类型 Objective-C 学习笔记 - part 8 - 快速枚举 Objective-C 学习笔记 - part 6 - 类别与扩展 Objective-C 学习笔记 - part 5 - 申明属性 Objective-C 学习笔记 - part 4 - 协议
Objective-C 学习笔记 - part 7 - 相关引用
沙加 · 2011-08-17 · via 博客园 - 沙加

上一章讲了对类的方法进行扩展, 相关引用就是为现存的 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;
}