美文网首页
分类+属性 (runtime)

分类+属性 (runtime)

作者: phpios | 来源:发表于2016-07-22 10:09 被阅读55次

    Student

    @interface Student : NSObject
    @property (nonatomic,assign) NSInteger age;
    @end
    
    @implementation Student
    @end
    

    Student + Category

    import "Student.h"
    @interface Student (Extention)
    @property (nonatomic,copy) NSString *name;
    @property (nonatomic,assign) NSInteger height;
    @end
    
    import "Student+Extention.h"
    import <objc/runtime.h>
    
    ////定义成常量  用C语言
    static char *nameKey = "nameKey";
    static char *heightKey = "heightKey";
    
    @implementation Student (Extention)
    
    - (void)setName:(NSString*)name{
        objc_setAssociatedObject(self, nameKey, name, OBJC_ASSOCIATION_COPY_NONATOMIC);
    }
    
    - (NSString *)name{
        return objc_getAssociatedObject(self, nameKey);
    }
    
    - (void)setHeight:(NSInteger)height{
      objc_setAssociatedObject(self, heightKey, @(height), OBJC_ASSOCIATION_ASSIGN);
    }
    
    - (NSInteger)height{
      return [objc_getAssociatedObject(self, heightKey) integerValue];
    }
    
    @end
    

    OBJC_ASSOCIATION_ASSIGN; //assign策略
    OBJC_ASSOCIATION_COPY_NONATOMIC; //copy策略
    OBJC_ASSOCIATION_RETAIN_NONATOMIC; // retain策略
    OBJC_ASSOCIATION_RETAIN;
    OBJC_ASSOCIATION_COPY;

    //id object 给哪个对象的属性赋值
    //const void *key 属性对应的key
    //id value  设置属性值为value
    //objc_AssociationPolicy policy  使用的策略,是一个枚举值,和copy,retain,assign是一样的,手机开发一般都选择NONATOMIC
    objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy);
    

    相关文章

      网友评论

          本文标题:分类+属性 (runtime)

          本文链接:https://www.haomeiwen.com/subject/yshijttx.html