Category 动态添加属性

来源:互联网 发布:python hbase api 编辑:程序博客网 时间:2024/04/29 20:32

了解OC的都应该知道,在一般情况下,我们是不能向Category中添加属性的,只能添加方法,但有些情况向,我们确实需要向Category中添加属性,而且很多系统的API也有一些在Category添加属性的情况。


iOS运行时机制简介

iOS运行时机制,简单来说,就是苹果给开发这提供的一套在运行时动态创建类、添加属性/方法(不止这些,还有一些其他功能)的API,它是一套纯C语言的API,使用相应的API就可以通过Category给一个原本存在的类添加属性。

//

//  NSObject+Extension.h

//  Target-Action

//

//  Created by ChenQing on 16/4/24.

//  Copyright © 2016 ChenQing. All rights reserved.

//


#import <Foundation/Foundation.h>


@interface NSObject (Extension)


@property (strong,nonatomic)NSDictionary *userInfo;


@end



//

//  NSObject+Extension.m

//  Target-Action

//

//  Created by ChenQing on 16/4/24.

//  Copyright © 2016 ChenQing. All rights reserved.

//


#import "NSObject+Extension.h"

#import <objc/runtime.h>

@implementation NSObject (Extension)


-(void)setUserInfo:(NSDictionary *)userInfo{

    objc_setAssociatedObject(self,@"userInfo", userInfo,OBJC_ASSOCIATION_RETAIN_NONATOMIC);

 //#import <objc/runtime.h>头文件
    //objc_setAssociatedObject需要四个参数:源对象,关键字,关联的对象和一个关联策略。
     
    //1 源对象self
    //2 关键字 唯一静态变量key associatedkey
    //3 关联的对象 userInfo
    //4 关键策略  OBJC_ASSOCIATION_ASSIGN
//    enum {
//        OBJC_ASSOCIATION_ASSIGN = 0,           若引用/**< Specifies a weak reference to the associated object. */
//        OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1, /**< Specifies a strong reference to the associated object.
//                                                *   The association is not made atomically. */
//        OBJC_ASSOCIATION_COPY_NONATOMIC = 3,   /**< Specifies that the associated object is copied.
//                                                *   The association is not made atomically. */
//        OBJC_ASSOCIATION_RETAIN = 01401,       /**< Specifies a strong reference to the associated object.
//                                                *   The association is made atomically. */
//        OBJC_ASSOCIATION_COPY = 01403          /**< Specifies that the associated object is copied.
//                                                *   The association is made atomically. */
//    };

}


-(NSDictionary *)userInfo{

//通过 objc_getAssociatedObject获取关联对象

    returnobjc_getAssociatedObject(self,@"userInfo");

}


@end


0 0
原创粉丝点击