为UIButton增加可传递的参数

之前,一直利用 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类型值,实际上可以传任何类型的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值