我可以标记 UIColor 吗? [英] Can I tag a UIColor?

查看:23
本文介绍了我可以标记 UIColor 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以标记一个不断变化的值以便从方法中轻松访问的 UIColor 吗?

Can I tag a UIColor that is constantly changing values for easy access from methods?

推荐答案

从 iPhone SDK 3.1 开始,您可以使用 objc_setAssociatedObject.你会做这样的事情:

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

注1:值必须是一个对象.您不能将整数设置为值.

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

要检索值:

id aTag = objc_getAssociatedObject(myColor, &keyObject);

注意 2: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);

(由于一个错误,这在 iPhone 模拟器中不起作用.请参阅这个问题 了解更多信息.)

(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.

注意:我并不是说这是处理问题的最佳方式.正如 Objective-C 编程指南所述,关联对象主要用于

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.

阅读所有相关信息此处.

这篇关于我可以标记 UIColor 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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