IOS-getter和setter方法

--点语法

可以不使用[student  age],用student.age来访问变量

虽然看起来student.age是直接访问变量,但本质还是调用了方法来访问变量


为什么要设计点语法?

方便程序员快速入手OC

简化程序设计

隐藏了内存管理细节

隐藏了多线程、同步、加锁细节

方法调用

Student *stu = [[Student alloc] init];

[stu setAge:100];

int age = [stu age];


点语法

stu.age = 100;

int age = stu.age;

点语法本质

其实点语法的本质还是方法调用

当使用点语法时,编译器会自动展开成相应的方法

stu.age = 10;    展开为  


[stu  setAge:10];


int  age = stu.age;     展开为

int  age = [stu  age];

@property

@property让编译器自动生成getter和setter的声明

@property int age;就可以代替下面的两行

- (int)age;   // getter

- (void)setAge:(int)newAge;  // setter

#import <Foundation/Foundation.h>

@interface Student {

int age;

}

- (int)age;   // getter

- (void)setAge:(int)newAge;  // setter


@property int age;

@end

@synthesize

@synthesize让编译器自动实现getter和setter

@synthesize age;就可以代替

- (int)age{

return age;

}

- (void)setAge:(int)newAge{

age = newAge;

}

#import "Student.h"

@implementation Student 

@synthesize age;

- (int)age{

return age;

}

- (void)setAge:(int)newAge{

age = newAge;

}

@end


在类内部可以直接访问成员变量,如
age = 100;
int  temp = age + 10;
self.age不是直接访问成员变量,而是调用了getter或者setter方法
self.age = 100; 
// 相当于 [self  setAge:100];
// 不要在setAge:中写self.age = 100; 会造成死循环
int  temp = self.age + 10;  // int  temp = [self  age] + 10;

@synthesize age = _age; 展开


- (int)age{

return _age;

}

- (void)setAge:(int)newAge{

_age = newAge;

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值