Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
412 views
in Technique[技术] by (71.8m points)

objective c - Avoid extra static variables for associated objects keys

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";

and then use is to store the object

objc_setAssociatedObject(self, ObjectTagKey, newObjectTag, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

and retrieve it

objc_getAssociatedObject(self, ObjectTagKey);

(example taken by 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.

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;

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.

Is this safe?

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...