开发者

Can I tag a UIColor?

Can I tag a UIColor that is constantly changing values for easy 开发者_如何转开发access from methods?


As of iPhone SDK 3.1, you can use objc_setAssociatedObject. You'd do something like:

objc_setAssociatedObject(myColor, infoObject, &keyObject, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

Note 1: the value must be an object. You can't set an integer as the value.

To retrieve the value:

id aTag = objc_getAssociatedObject(myColor, &keyObject);

Note 2: the keyObject must exactly the same object that you used when setting the value. It won't work if you send in another object with the same value.

If you later want to release the tag value:

objc_setAssociatedObject(myColor, nil, &keyObject, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

(Due to a bug this doesn't work in the iPhone simulator. See this question for more info.)

You can also read this post which touches on using this method for storing keys.

Note: I'm not saying this is the best way of handling the problem. As the Objective-C programming guide states, associated objects are mainly intended for situations where

you do not have access to the source code for the class, or if for binary-compatibility reasons you cannot alter the layout of the object.

Read all about it here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜