美文网首页
iOS 类扩展和分类(类别)

iOS 类扩展和分类(类别)

作者: xu1Peng | 来源:发表于2021-09-17 16:53 被阅读0次
    #import "secondViewController.h"
    #import <objc/runtime.h>
    
    /**
     类扩展,可以增加成员变量、属性、方法
     */
    @interface secondViewController ()
    - (void)reset1;
    @end
    
    /**
      分类或者类别。只能增加方法,不能增加成员变量、属性(其实也是可以加的,利用通过runtime解决无setter/getter的问题而已,_成员变量依然报错)
      原因:分类的指针结构体中,根本没有属性列表,只有方法列表
     */
    @interface secondViewController (category)
    @property(nonatomic,copy) NSString *name;
    - (void)reset;
    @end
    
    @implementation secondViewController (category)
    
    static NSString *nameWithSetterGetterKey = @"nameWithSetterGetterKey";   //定义一个key值
    //运行时实现setter方法
    - (void)setName:(NSString *)nameWithSetterGetter {
        objc_setAssociatedObject(self, &nameWithSetterGetterKey, nameWithSetterGetter, OBJC_ASSOCIATION_COPY);
    }
    //运行时实现getter方法
    - (NSString *)name{
        return objc_getAssociatedObject(self, &nameWithSetterGetterKey);
    }
    
    - (void)reset{
        NSLog(@"响应了分类中的方法");
    }
    @end
    
    @implementation secondViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        self.view.backgroundColor = [UIColor systemGreenColor];
        
        self.name = @"hahhaa";
        [self reset];
        [self reset1];
    }
    
    
    - (void)reset1{
        NSLog(@"响应了类扩展中的方法");
    }
    

    相关文章

      网友评论

          本文标题:iOS 类扩展和分类(类别)

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