5、OC —— @property和@synthesize

1、什么是 @property 和 @synthesize ?

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


2、为什么要用 @property 和 @synthesize ?

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

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


3、怎么使用 @property 和 @synthesize ?

    Student.h

#import <Foundation/Foundation.h>

@interface Student : NSObject

@property int age;

// 相当于
// - (void)setAge:(int)newAge;
// - (int)age;

@end

    Student.m

@import "Student.h"

@implementation Student

@synthesize age;

// 相当于
// - (void)setAge:(int)newAge {
//     age = newAge;
// }
// - (int)age {
//     return age;
// }

@end


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

    Student.m

@import "Student.h"

@implementation Student

@synthesize age = _age;

// 相当于
// - (void)setAge:(int)newAge {
//     _age = newAge;
// }
// - (int)age {
//     return _age;
// }

@end


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

    Student.m

@import "Student.h"

@implementation Student

// @synthesize age = _age;

@end


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

    Student.m

@import "Student.h"

@implementation Student

- (int)age {
    _age += 10;
    return _age;
}

@end



你可能感兴趣的:(5、OC —— @property和@synthesize)