首页 > 代码库 > iOS复习笔记5:内存管理之set方法

iOS复习笔记5:内存管理之set方法

1 alloc和release成对出现
2 set方法
2.1 基础类型直接赋值
2.2 OC对象:判断不等、retain新的,释放旧的,再赋值
3 dealloc方法
3.1 一定要调用[super dealloc];且放在最后
3.2 self拥有的对象要做一次release


@interface Book
{
	int _price;
}


- (void)setPrice:(int)price;
- (int)price;


@end


@implementation Book


- (void)setPrice:(int)price
{


	_price = price;
}


- (int)price
{
	return _price;
}


- (void)dealloc
{
	[_book release];
	_book = nil;


	[super dealloc];
}


@end


@interface Person
{
	Book* _book;
}


- (void)setBook:(Book*)book;
- (Book*)book;


@end


@implementation Person


- (void)setBook:(Book*)book
{
	// retain新的,release旧的,把新的赋给旧的
	if (_book != book){
		[book retain];
		[_book release];
		_book = book;
	}


	/* 可以简写为:
	if (_book != book){
		[_book release];
		_book = [book retain];
	}
	*/
}


- (Book*)book
{
	return _book;
}


@end



#import <Foundation/Foundation.h>


int main()
{
	Person* person = [[Person alloc] init];


	Book* book = [[Book alloc] init];
	[person setBook:book];
	[book release];
	book = nil;


	[person release];


	return 0;
}


iOS复习笔记5:内存管理之set方法