iOS:class_copyIvarList和class_copyPropertyList

 

大家好!我是OB。今天聊聊成员变量和属性

一、成员变量和属性是什么?

下面的就是成员变量

@interface Animal: NSObject
{
    NSString *_name;
}
@end

这里是属性:而且property出来的属性会自动生成_address的成员变量

@interface Animal: NSObject

@property (nonatomic, copy)NSString *address;

@end

通过runtime遍历成员变量和属性:分别利用class_copyIvarList和class_copyPropertyList方法


#import <objc/runtime.h>

@interface Animal: NSObject
{
    NSString *_name;
}
@property (nonatomic, copy)NSString *address;
@end

@implementation Animal
@end

@interface Cat: Animal
{
    NSString *age;
}
@property (nonatomic, copy)NSString *aliys;

- (NSString *)testName;
- (void)setTestName:(NSString *)testName;
@end


@implementation Cat

- (NSString *)testName {
    return (NSString *)objc_getAssociatedObject([self class], "key_testName");
}
- (void)setTestName:(NSString *)testName {
    objc_setAssociatedObject([self class], "key_testName", testName, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

@end


int main(int argc, char * argv[]) {
    @autoreleasepool {

        Cat *cat = [[Cat alloc]init];
        cat.testName = @"i_am_OB";
        NSLog(@"testName : %@",cat.testName);
        unsigned ivarCount = 0;
        Ivar *ivars = class_copyIvarList([cat class], &ivarCount);
        for (int i = 0; i < ivarCount; i ++) {
            Ivar ivar = ivars[i];
            const char *ivarName = ivar_getName(ivar);
            const char *ivartype = ivar_getTypeEncoding(ivar);
            NSLog(@"%s:%s",ivarName,ivartype);
        }
        unsigned propertyCount = 0;
        objc_property_t *propertys = class_copyPropertyList([cat class], &propertyCount);
        for (int i = 0; i < propertyCount; i ++) {
            const char * propertyName = property_getName(propertys[i]);
            NSLog(@"%s",propertyName);
        }
        
    }
}

打印如下

2020-07-10 11:27:09.071077+0800 Test[6946:337368] testName : i_am_OB
2020-07-10 11:27:09.071694+0800 Test[6946:337368] age:@"NSString"
2020-07-10 11:27:09.071782+0800 Test[6946:337368] _aliys:@"NSString"
2020-07-10 11:27:09.071853+0800 Test[6946:337368] aliys

 

发现class_copyPropertyList中只会出现@property属性,没有成员变量,而class_copyIvarList都有,成员变量和属性都能访问到,但是都不能访问到父类的成员变量

而且通过关联对象方法添加的属性既不在PropertyList中也不再IvarList中,说明利用runtime添加的属性并不是真正的属性(对象的内存布局不能改变),而是在内存中,另外开辟了内存,把值和key放入AssociationsHashMap中,并关联上了这个对象。取值也是从AssociationsHashMap中取

 

都不能访问到父类的成员变量?

这个和C++中,class的默认继承权限可能有关系。c++中class的默认继承权限是private,也就是不能访问父类的成员函数,而c++中的struct是可以继承,并且默认继承权限是public

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值