大家好!我是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

2万+

被折叠的 条评论
为什么被折叠?



