iOS 成员变量和属性的关系

#import


//Public: is available an accessible from anywhere

//Protected: is available only to subclasses

//Private: is available to the class only

//Package: is available from that package only aka Framework or Library


@interface ViewController : UIViewController {

    

    //成员变量

    

    //如果一个变量是public,我觉得不需要写在这里,直接写成property就可以,因为写成property,会自动生成一个 _ + 属性名的成员变量

    // 例如,如果有一个属性是 propertyName,则会生成成员变量_propertyName,如果此处有_propertyName,则不生成

//    @public

//        NSString *_publicString;

    

    @protected

        NSString *protectedString;

    

//    @private

//        NSString* privateString;

    

//    @package

//        BOOL packageVar;

}


//属性变量

@property(nonatomic, copy) NSString *propertyString;


@property(nonatomic, copy) NSString *publicString;


@property(nonatomic, copy) NSString *foo;



@end


#import "ViewController.h"



@interface ViewController ()


//如果自己内部需要settergetter来实现一些东西,就在.m文件的类目里用property来声明

//写在这里的property不会生成成员变量

@property(nonatomic, strong) UIButton *loginButton;


@end



@implementation ViewController {

    //私有变量一般写在这里

    @private

        NSString* privateString;

}



@synthesize foo;


//@dynamic foo;


- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    

//    privateString = @"私有变量";

//    

//    NSLog(@"%@", privateString);   

}


- (void)setLoginButton:(UIButton *)loginButton {


    self.loginButton = loginButton;

}


- (UIButton *)loginButton {


    return self.loginButton;

}


- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}



@end



- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // Override point for customization after application launch.

    

    ViewController *newViewController = [[ViewController alloc] init];

    

    newViewController.propertyString = @"这是属性字符串";

    

    unsigned int count = 0; //count记录变量的数量

    

    // 获取类的所有成员变量

    Ivar *members = class_copyIvarList([ViewController class], &count);

    for (int i = 0; i < count; i++) {

        Ivar ivar = members[i];

        // 取得变量名并转成字符串类型

        const char *memberName = ivar_getName(ivar);

        NSLog(@"变量名 = %s",memberName);

    }

    // 获取类的所有成员属性

    objc_property_t *properties =class_copyPropertyList([ViewController class], &count);

    for (int i = 0; i

    {

        objc_property_t property = properties[i];

        const char* char_f =property_getName(property);

        NSString *propertyName = [NSString stringWithUTF8String:char_f];

        NSLog(@"属性名 = %@",propertyName);

    }

    

    return YES;

}




你可能感兴趣的:(iOS,OC)