避免为关联的对象键添加额外的静态变量 [英] Avoid extra static variables for associated objects keys

查看:100
本文介绍了避免为关联的对象键添加额外的静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用关联对象时,可从iOS 4和OSX 10.6开始使用Objective-C运行时功能,有必要定义一个用于在运行时存储和检索对象的键.

When using associated objects, an Objective-C runtime feature available starting from iOS 4 and OSX 10.6, it's necessary to define a key for storing and retrieving the object at runtime.

典型用法是定义密钥,如下所示

The typical usage is defining the key like follows

static char const * const ObjectTagKey = "ObjectTag";

然后使用来存储对象

objc_setAssociatedObject(self, ObjectTagKey, newObjectTag, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

并检索

objc_getAssociatedObject(self, ObjectTagKey);

(示例由 http ://oleb.net/blog/2011/05/faking-ivars-in-objc-categories-with-associative-references/)

是否有一种更干净的方法来定义关联的对象键,而无需涉及额外变量的声明?

Is there a cleaner way to define the associated object key, that doesn't involve the declaration of extra variables?

推荐答案

根据此 Gwynne Raskind ),有.

According to this blog entry by Erica Sadun (whose credits go to Gwynne Raskind), there is.

objc_getAssociatedObjectobjc_getAssociatedObject需要一个密钥来存储对象.此类密钥必须是常量void指针.因此,最后我们只需要一个固定的地址,该地址会随着时间的流逝而保持不变.

objc_getAssociatedObject and objc_getAssociatedObject require a key to store the object. Such key is required to be a constant void pointer. So in the end we just need a fixed address that stays constant over time.

事实证明,@selector实现实现了我们所需的功能,因为它使用的是固定地址.

It turns out that the @selector implementation provides just about what we need, since it uses fixed addresses.

因此,我们可以摆脱键声明,而只需使用属性的选择器地址即可.

We can therefore just get rid of the key declaration and simply use our property's selector address.

因此,如果您在运行时关联一个属性,如

So if you are associating at runtime a property like

@property (nonatomic, retain) id anAssociatedObject;

我们可以为其getter/setter提供动态的实现,

we can provide dynamic implementations for its getter/setter that look like

- (void)setAnAssociatedObject:(id)newAssociatedObject {
     objc_setAssociatedObject(self, @selector(anAssociatedObject), newAssociatedObject, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (id)anAssociatedObject {
    return objc_getAssociatedObject(self, @selector(anAssociatedObject));
}

比为每个关联的对象定义一个额外的静态变量键非常整洁而且绝对干净.

Very neat and definitely cleaner than defining an extra static variable key for every associated object.

由于这是依赖于实现的,所以一个合理的问题是:它容易中断吗? 引用博客条目

Since this is implementation-dependent, a legitimate question is: will it easily break? Quoting the blog entry

苹果可能必须实施一个全新的ABI来实现

Apple would probably have to implement a completely new ABI for that to happen

如果我们认为这些话是真实的,那么这是相当安全的.

If we take those words to be true, it's then reasonably safe.

这篇关于避免为关联的对象键添加额外的静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆