ok; //声明Book是一个类
@interface Student : NSObject
//assign参数代表set方法直接赋值(默认的)
//getter方法是指定getter方法的名字
@property (nonatomic, assign, getter=getStudentAge) int age;
//这里的retain代表:release旧值,retain新值
//(注意,基本数据类型不能写retain参数)
@property (nonatomic, retain) Book *book;
- (void)setBook:(Book *)book;
- (id)initStudent:(int)age;
@end
#import "Student.h"
#import "Book.h"
@implementation Student
//构造函数
- (id)initStudent:(int)age {
if(self = [super init]) {
_age = age;
}
NSLog(@"年龄为%d的学生被创建了", _age);
return self;
}
//析构函数
- (void)dealloc{
self.book = nil; //调用setter方法
[_book release];
NSLog(@"年龄为%d的学生被释放了", _age);
[super dealloc];
}
@end
自动释放池
自动释放池是OC里面的一种内存自动回收机制,一般可以将一些临时变量添加到自动释放池中,统一回收释放。当自动释放池销毁时,池里的所有对象都会调用一次release方法。OC对象只需要发送一条autorelease消息,就会把这个对象添加到最近的自动释放池中(栈顶的释放池)。
autorelease实际上只是把release的调用延迟了,对于每一次autorelease,系统只是把该对象放入当前的autorelease pool中,当该pool被释放时,该pool中的所有对象会调用一次release方法。
#import "Student.h"
#import "Book.h"
@implementation Student
//创建静态方法构造对象
+ (id)student {
Student *stu = [[[Student alloc] init] autorelease];
return stu;
}
//创建带参数的静态方法构造对象
+ (id)studentWithAge:(int)age {
Student *stu = [self student];
stu.age = age;
return stu;
}
//构造函数
- (id)initStudent:(int)age {
if(self = [super init]) {
_age = age;
}
NSLog(@"年龄为%d的学生被创建了", _age);
return self;
}
//析构函数
- (void)dealloc{
self.book = nil; //调用setter方法
[_book release];
NSLog(@"年龄为%d的学生被释放了", _age);
[super dealloc];
}
@end
int main(int argc, const char * argv[]) {
//代表创建一个自动释放池
@autoreleasepool {
//第一种写法
Student *stu = [[[Student alloc] initStudent:21] autorelease];
Student *stu1 = [[[Student alloc] initStudent:21] autorelease];
} //当括号结束后,池子将被销毁
//如果自动释放池被销毁,池里面的所有对象都会调用release方法
@autoreleasepool {
//第二种写法
Student *stu2 = [[Student alloc] initStudent:21];
[stu2 autorelease];
}
@autoreleasepool {
//第三种写法(推荐)
//不用手动释放
Student *stu3 = [Student student];
}
return 0;
}