4--OC --合成存取器方法

1. 从OC 2.0开始就已经可以自动生成设置函数方法和获取函数方法(统称为存取器方法)。

什么是 @property 和 @synthesize ?

    @property 和 @synthesize 实际是开发工具 Xcode 对代码的一种替换,我不确定它们是否是OC的语法,毕竟IOS开发基本是在 Xcode 上进行,它们的主要作用就是自动帮我们生成 getter 和 setter 方法,大大简化我们的代码,并且大部分人都这么做,有利于团队开发。

为什么要用 @property 和 @synthesize ?

    a)当我们在 .h 文件写一个变量时,需要声明它的 getter 和 setter 方法,然后去 .m 文件实现,几个变量还行,如果数量多了, .h 和 .m 文件里就会充斥着代码几乎类似的 getter 和 setter 方法。

    b)使用 @property 和 @synthesize 时就不需要再继续写 getter 和 setter 方法的声明和实现了,甚至连定义变量都不需要了,开发工具会自动帮我们把变量以及它的 getter 和 setter 方法都实现,虽然我们看不到,but they are there.

 怎么使用 @property 和 @synthesize ?

    Student.h

1
2
3
4
5
6
7
8
9
10
11
#import <Foundation/Foundation.h>
 
@interface Student : NSObject
 
@property int age;
 
// 相当于
// - (void)setAge:(int)newAge;
// - (int)age;
 
@end

    Student.m

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@import "Student.h"
 
@implementation Student
 
@synthesize age;
 
// 相当于
// - (void)setAge:(int)newAge {
//     age = newAge;
// }
// - (int)age {
//     return age;
// }
 
@end

    当然我们之前说过,成员变量最好开头加上下划线,例如:_age,在@synthesize后面赋值即可,开发工具会默认生成 _age 变量而不是 age

    Student.m

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@import "Student.h"
 
@implementation Student
 
@synthesize age = _age;
 
// 相当于
// - (void)setAge:(int)newAge {
//     _age = newAge;
// }
// - (int)age {
//     return _age;
// }
 
@end

    在 Xcode4.5以后,@synthesize可以省略不写,但它还是确实在那的,只是你看不见,它会默认给成员变量加下划线

    Student.m

1
2
3
4
5
6
7
@import "Student.h"
 
@implementation Student
 
// @synthesize age = _age;
 
@end

    当你不拘于标准的 getter 和 setter 方法时,即想在 getter 或 setter 方法中添加一点自己的东西,这时你就只能自己重写了,开发工具无能为力

    Student.m

1
2
3
4
5
6
7
8
9
10
@import "Student.h"
 
@implementation Student
 
- (int)age {
    _age += 10;
    return _age;
}
 
@end
原文地址:https://www.cnblogs.com/stephenmc/p/5169758.html