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
复制代码

 

posted @   cocoajin  阅读(429)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示