美文网首页
Category分类注意事项

Category分类注意事项

作者: SimpleSJ | 来源:发表于2018-11-19 11:32 被阅读0次

    1.分类用来添加方法,不能用来添加属性(可以利用运行时特性,动态绑定属性来实现)

    @proprety只会生成getter/setter方法的声明, 不会生成实现和私有成员变量.

    @interface NSObject (func)
    @property (strong,nonatomic)NSString *vcName;
    
    @end
    
    
    #import "NSObject+func.h"
    #import <objc/message.h>
    @implementation NSObject (func)
    -(void)setVcName:(NSString *)vcName{
        objc_setAssociatedObject(self, @"vcName", vcName, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    -(NSString *)vcName{
        return objc_getAssociatedObject(self, @"vcName");
    }
    @end
    
    ViewController.m
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        self.vcName = @"aaa";
        NSLog(@"%@",self.vcName);
    }
    
    输出:aaa
    

    2.分类可以访问原来类中的成员变量

    3.如果分类和原来类出现同名的方法, 优先调用分类中的方法, 原来类中的方法会被忽略

    @implementation Person
    
    - (void)sleep
    {
        NSLog(@"%s", __func__);
    }
    @end
    
    @implementation Person (SJ)
    - (void)sleep
    {
        NSLog(@"%s", __func__);
    }
    @end
    
    int main(int argc, const char * argv[]) {
        Person *p = [[Person alloc] init];
        [p sleep];
        return 0;
    }
    
    输出结果:
    -[Person(SJ) sleep]
    

    4.知识点补充,开发中很少用到:多个分类中拥有同一个方法,使用时,调用最后编译的分类中的方法

    • 假设一个Person类拥有三个分类,Person+funcOne、Person+funcTwo、Person+funcThree,三个分类都有一个eat方法,执行最后一个编译的分类中的方法.
    #import <Foundation/Foundation.h>
    #import "Person.h"
    #import "Person+funcOne.h"
    #import "Person+funcTwo.h"
    #import "Person+funcThree.h"
    int main(int argc, const char * argv[]) {
        
        Person *p = [[Person alloc]init];
        
        [p eat];
        return 0;
    }
    
    image.png
    输出:-[Person(funcTwo) eat]
    

    相关文章

      网友评论

          本文标题:Category分类注意事项

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