之前,一直利用 button的 tag 进行数据的传递和条件判断。
现在的情况用tag很难处理,因此,尝试了几种方式。
最后,找到了 OBJC_ASSOCIATION_RETAIN_NONATOMIC 。
1、首先要引入
#import <objc/runtime.h>
2、赋值
// 创建一个button
self.showButton = [[UIButton alloc]init];
// 给 button 设置一个key = uuid ,value = owner[@"uuid"]
objc_setAssociatedObject(self.showButton, "uuid", owner[@"uuid"], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
3、取值
-(void)someMethod:(id)button
{
SomeViewController *controller = [[SomeController alloc]init];
NSString *uuidString = objc_getAssociatedObject(button, "uuid");
controller.uuid = uuidString;
}
// 赋值
objc_setAssociatedObject(button, "key",@"value", OBJC_ASSOCIATION_RETAIN_NONATOMIC);
// 取值
objc_getAssociatedObject(button, "key");
注意:
1、key就是以双引号包围起来的字符串,前面没有 @ 符号。
2、value是以@开始的 oc 的字付串。
赋值与取值的方法可以不在一个类中。
只要能获得button,在任何地方都可以得到在button中设置的值。
/**
* Sets an associated value for a given object using a given key and association policy.
*
* @param object The source object for the association.
* @param key The key for the association.
* @param value The value to associate with the key key for object. Pass nil to clear an existing association.
* @param policy The policy for the association. For possible values, see “Associative Object Behaviors.”
*
* @see objc_setAssociatedObject
* @see objc_removeAssociatedObjects
*/
OBJC_EXPORT void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy)
OBJC_AVAILABLE(10.6, 3.1, 9.0, 1.0);
/**
* Returns the value associated with a given object for a given key.
*
* @param object The source object for the association.
* @param key The key for the association.
*
* @return The value associated with the key \e key for \e object.
*
* @see objc_setAssociatedObject
*/
OBJC_EXPORT id objc_getAssociatedObject(id object, const void *key)
OBJC_AVAILABLE(10.6, 3.1, 9.0, 1.0);
这里只是传递了一个NSString类型值,实际上可以传任何类型的。