标签:c style class blog code tar
当你定义了一系列的变量时,需要写很多的getter和setter方法,而且它们的形式都是差不多的,,所以Xcode提供了@property
和@synthesize属性,@property用在 .h 头文件中用作声明,@synthesize用在.m 文件中用于实现。
如下,新建一个基于“Command Line Tool”的项目,名为“property”,再新建一个Student类,
传统的写法是:
Student.h
-
-
-
-
-
-
-
-
- #import <Foundation/Foundation.h>
-
- @interface Student : NSObject
- {
- int age;
- int no;
- }
-
-
- - (int)age;
- - (void)setAge:(int)newAge;
-
-
- - (int)no;
- - (void)setNo:(int)newNo;
-
- @end
Student.m
-
-
-
-
-
-
-
-
- #import "Student.h"
-
- @implementation Student
-
-
- - (int)age
- {
- return age;
- }
- -(void)setAge:(int)newAge
- {
- age = newAge;
- }
-
-
- - (int)no
- {
- return no;
- }
- - (void)setNo:(int)newNo
- {
- no = newNo;
- }
-
- @end
main.m
-
-
-
-
-
-
-
-
- #import <Foundation/Foundation.h>
- #import "Student.h"
-
- int main(int argc, const char * argv[])
- {
-
- @autoreleasepool {
-
-
- Student *stu = [[Student alloc] init];
- stu.age = 100;
- NSLog(@"age is %i", stu.age);
-
- [stu release];
-
- }
- return 0;
- }
------------------------------------------------------------------------------------------------------------------------
用@property和@synthesize的写法是:
Student.h
-
-
-
-
-
-
-
-
- #import <Foundation/Foundation.h>
-
- @interface Student : NSObject
- {
- int age;
- int no;
- }
-
-
- @property int age;
- @property int no;
-
-
- @end
Student.m
-
-
-
-
-
-
-
-
- #import "Student.h"
-
- @implementation Student
-
-
-
-
-
- @synthesize age,no;
-
- @end
main.m
-
-
-
-
-
-
-
-
- #import <Foundation/Foundation.h>
- #import "Student.h"
-
- int main(int argc, const char * argv[])
- {
-
- @autoreleasepool {
-
-
- Student *stu = [[Student alloc] init];
- stu.age = 100;
- NSLog(@"age is %i", stu.age);
-
- [stu release];
- }
- return 0;
- }
几点说明:
1.在Xcode4.5及以后的版本中,可以省略@synthesize ,编译器会自动帮你加上getter 和 setter
方法的实现,并且默认会去访问
_age这个成员变量,如果找不到_age这个成员变量,会自动生成一个叫做 _age的私有成员变量。
2.视频教学中建议变量名用"_"前缀作为开头,但我看big Nerd 那本书里是不用的,个人也比较习惯 big Nerd
的那种写法,所以变量名就不加前缀了。Y^o^Y
摘自:http://blog.csdn.net/chaoyuan899/article/details/10310719
ios的@property属性和@synthesize属性(转),布布扣,bubuko.com
ios的@property属性和@synthesize属性(转)
标签:c style class blog code tar
原文地址:http://www.cnblogs.com/SharkBin/p/3762253.html