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;
}


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。