码迷,mamicode.com
首页 > 移动开发 > 详细

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

时间:2015-01-29 14:40:55      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:内存管理   objective-c   ios   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方法

标签:内存管理   objective-c   ios   set方法   

原文地址:http://blog.csdn.net/xufeng0991/article/details/43269741

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!