OC实例变量和属性@synthesize与@property

Student.h

 1 #import <Foundation/Foundation.h>
 2 
 3 @interface Student : NSObject
 4 {
 5     // 实例变量命名 以 _开头,和系统命名规范一致;
 6     
 7     //1:public的实例变量可以用 -> 方式访问;
 8 @public
 9     NSString *_publicName;
10     //2:默认为protected 权限;子类可以继承;
11 @protected
12     NSString *_protectedName;
13     
14     //4:@property 使用系统 会加 _的实例变量,如果不加;
15     float number; //这是一个实例变量  和系统 加的 _bumber是两个;用@synthesize number 把系统加的 _的 等于 当前的 number;
16 }
17 
18     //3:只写一个 @property age;默认加上 getter,setter方法 和一个 实例变量 _age;
19 @property(nonatomic,readwrite,assign)int age;   //相当于加setter , getter , 并加实例变量 _age;
20 
21 
22     //4:@property 与 @synthesize;
23 @property(nonatomic,readwrite,assign)float number;
24 
25 
26 - (void)sayHello;
27 @end
View Code

Student.m

#import "Student.h"

@implementation Student

//4:@property 是方法的声明,@synthesize 是方法的实现;
@synthesize number; //默认加的 _number实例变量会没有;变成了number;

//@synthesize number = _number; //默认加的 _number实例变量存在;

- (void)sayHello
{
    _protectedName = @"小明";
    NSLog(@"%@ hello",_protectedName);
    
}
View Code

main.m

 1 #import <Foundation/Foundation.h>
 2 #import "Student.h"
 3 
 4 int main(int argc, const char * argv[])
 5 {
 6 
 7     Student *student = [[Student alloc]init];
 8 
 9     //1:实例变量 public 权限的可以用 -> 方法;
10     student->_publicName = @"Steven";
11     NSLog(@"%@",student->_publicName);
12     
13     //2:实例变量 protected,private只能在类内部使用;
14     [student sayHello];
15     
16     //3:@property 属性 相当于定义了 getter,setter方法,就可以用对象在外部调用了;
17     student.age = 18;
18     NSLog(@"%d",student.age);
19     
20     //4: @property 是方法的声明,@synthesize 是方法的实现;
21     student.number = 1001;
22     NSLog(@"%f",student.number);
23     
24     [student release];
25   
26     
27     
28     return 0;
29 }
View Code
原文地址:https://www.cnblogs.com/cocoajin/p/3081683.html