• iOS 关联对象(Associated Object)


    1、category需要添加属性,可以使用关联对象来扩展对象

    objc_setAssociatedObject(id _Nonnull object, const void * _Nonnull key,
                             id _Nullable value, objc_AssociationPolicy policy)
    objc_getAssociatedObject(id _Nonnull object, const void * _Nonnull key)
    objc_removeAssociatedObjects(id _Nonnull object)
    Associated Object

    id object  被关联的对象

    const void *key  关联的key,唯一

    id value  关联的对象

    objc_AssociationPolicy policy  内存管理的策略

    remove  移除一个管理对象

    @property (nonatomic, copy) NSString *cid;
    - (void)setCid:(NSString *)cid
    {
        objc_setAssociatedObject(self, &kStringKey, cid, OBJC_ASSOCIATION_COPY_NONATOMIC);
    }
    - (NSString *)cid
    {
        return objc_getAssociatedObject(self, &kStringKey);
    }
    添加属性

    2、为UIButton类别添加点击block

    // UIButton+Block.h
    typedef void (^ButtonBlock)(id sender);
    - (void)handleWithBlock:(ButtonBlock)block;
    // UIButton+Block.m
    static const char kButtonKey;
    - (void)handleWithBlock:(ButtonBlock)block
    {
        if (block)
        {
    //        objc_setAssociatedObject(self, @selector(btnAction:), block, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
            objc_setAssociatedObject(self, &kButtonKey, block, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        }
        [self addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    - (void)btnAction:(id)sender
    {
    //    ButtonBlock block = objc_getAssociatedObject(self, @selector(btnAction:));
        ButtonBlock block = objc_getAssociatedObject(self, &kButtonKey);
        if (block)
        {
            block(sender);
        }
    }
    UIButton+Block
  • 相关阅读:
    pycharm 中查找替换功能
    Python中括号的区别及用途
    python:return
    WAMPSERVER 启动不了APACHE原因
    Python为什么如此不同?
    Python初试云雨情
    mariadb 的日志
    MySql 之UUID()
    python 自建爬虫复用简单框架(gevent异步)
    python分布式进程
  • 原文地址:https://www.cnblogs.com/chenyanliang/p/9675523.html
Copyright © 2020-2023  润新知