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

推荐订阅源

B
Blog
A
About on SuperTechFans
Microsoft Security Blog
Microsoft Security Blog
Y
Y Combinator Blog
罗磊的独立博客
J
Java Code Geeks
人人都是产品经理
人人都是产品经理
MongoDB | Blog
MongoDB | Blog
The GitHub Blog
The GitHub Blog
G
Google Developers Blog
U
Unit 42
Microsoft Azure Blog
Microsoft Azure Blog
博客园 - Franky
Jina AI
Jina AI
F
Fortinet All Blogs
H
Help Net Security
B
Blog RSS Feed
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Last Week in AI
Last Week in AI
博客园 - 司徒正美
云风的 BLOG
云风的 BLOG
M
MIT News - Artificial intelligence
C
Check Point Blog
GbyAI
GbyAI

博客园 - 沙加

前端设计模式之 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;
}