通过runtime验证property声明是否会创建ivar

本文做关于ivar的测试:

1.@property (nonatomic, strong)NSStirng*property1;这个声明是否编译器会生成一个ivar变量

2.property声明中声明为weak

3.property声明为assin

具体测试代码如下:

#import <Foundation/Foundation.h>

@interface IvarTest : NSObject
{
    NSString*ivar1;
    NSString*ivar2;
}
@property(nonatomic, strong)NSString*property1;
@property(nonatomic, strong)NSString*property2;
@end



#import "IvarTest.h"
@interface IvarTest()

@property(nonatomic, strong)NSString*property3;
@property(nonatomic, strong)NSString*property4;
@property(nonatomic, weak)NSString*property5;
@property(nonatomic, assign)NSString*property6;

@end

@implementation IvarTest
{
    NSString*ivar3;
    NSString*ivar4;
}
@end


#import "ViewController.h"
#import "IvarTest.h"
#import <objc/runtime.h>

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    unsigned int count;
    Ivar *ivars = class_copyIvarList([IvarTest class], &count);
    
    for (unsigned int i = 0; i < count; ++i)
    {
        Ivar ivar = ivars[i];
        const char *ivarName = ivar_getName(ivar);
        NSString*ivarNameString = [NSString stringWithUTF8String:ivarName];
        NSLog(@"%@",ivarNameString);
    }

}

@end

  运行后打印结果为:

 

2016-04-28 16:40:13.979 IvarTest[31253:260489] ivar1

2016-04-28 16:40:13.979 IvarTest[31253:260489] ivar2

2016-04-28 16:40:13.979 IvarTest[31253:260489] ivar3

2016-04-28 16:40:13.979 IvarTest[31253:260489] ivar4

2016-04-28 16:40:13.980 IvarTest[31253:260489] _property1

2016-04-28 16:40:13.980 IvarTest[31253:260489] _property2

2016-04-28 16:40:13.980 IvarTest[31253:260489] _property3

2016-04-28 16:40:13.980 IvarTest[31253:260489] _property4

2016-04-28 16:40:13.980 IvarTest[31253:260489] _property5

2016-04-28 16:40:13.980 IvarTest[31253:260489] _property6

 

说明,property声明后,就会生成对应的ivar变量,property声明的是weak,assign都会生成对应的ivar变量

posted on 2016-04-28 17:15  wxm5558  阅读(211)  评论(0编辑  收藏  举报