1、set,get方法
stu.age = 10; //等价于[stu setAge:10],编译器编译时会把该句自动转换[stu setAge:10]。
int age = stu.age;//等价于int age = [stu age];
2、释放对象内存
Student *stu =[ [Student alloc] init];
[stu release];
上面这两句等价于Student *stu =[[[Student alloc] init] autolease];
说明:释放对象都需要调用release方法,只是静态方法已经封装了autolease方法,不用我们去再次去调用release方法了,但是自己创建的对象,还需要手动管理内存,所以要手动调用一次release方法。
3、新建对象
Student *student = [Student new];
等价于 Student *student = [[Student alloc] init];
4、set,get方法的另一种写法
在.h声明文件中:
#include<Foundation/Foundation.h>
@interface Student : NSObject{
int age;
int no;
float heigh;
}
-(void)setAge:(int) newNo;
-(int)age;
-(void)setNo:(int) newNo;
-(int)no;
-(void)setHeight:(float)newHeight;
-(float)height;
@end
等价于以下写法
#include<Foundation/Foundation.h>
@interface Student : NSObject{
int age;
int no;
float height;
}
@property int age;//当编译器遇到@property时,会自动展开成age的getter和setter的声明
@property int no;
@property float height;
@end
在.m文件中也要有相应的写法:
#import<Foundation/Foundation.h>
@implementation Student
@synthesize age;//会在.h文件自动生成一个age成员变量
//上面那句相当于以下代码:
//-----------------------------------------------------------------------------------
//-(void)setAge : (int) newAge{
//age = newAge;
// }
// -(int)age{
// return age;
// }
//-----------------------------------------------------------------------------------
@synthesize no;
@synthesize height;
//也可以把上面三句写成一句代码
//@synthesize age,no,height;
//如果要给自定义的成员变量如:_age赋值,则可写成
//@synthesize age = _age;//表示在.h声明文件中setAge方法要给_age这个成员变量赋值。
//即等价于
//-(void) setAge : (int) newAge{
// _age = newAge;
//}
//-(int) age{
// return _age;
//}
@end
总结:
property会自动生成getter和setter方法的声明。
synthesize会自动生成getter和setter方法的实现。
注意:XCODE4..5以上版本只需在声明文件写@property即可,不用在实现文件写@sythesize语句了,它会自动帮我们生成,同时也会自动生成带下划线前缀的成员变量,如:@property int age;他会自动生成成员变量_age。
5、setter方法释放内存的等效语句写法:
在Student.m文件中:
@implementation Student
#pragam mark setter方法
-(void) setBook : (Book *) book{
if(_book != book){
[_book release];
_book = [book retain];
}
}
//上面这个setter方法可以在Student.h文件中简写成:@property (retain) Book *book;//该retain会自动release旧值,retain新值。
#pragam mark 回收内存
-(void)dealloc{
[_book release];
[_card release];
[super dealloc];
}
}
6、释放内存时可以用self.book = nil;
也可以用[book setBook : nil];
也等价于[_book release];