内存管理2-set方法的内存管理-程序解析

创建class Book

.h 有@ property float price;  //@synthesize 自动

------------

创建class Student

#import "Book.h"

.h 有@property int age;

@property Book *book;         //@synthesize 自动

--------------

验证Student对象是否回收

Student.m

-(void)dealloc{

NSLog(@"Student :%i 被销毁了",_age);

[super dealloc];

}

--------------

为了方便访问_age 创建可以传入_age 的构造方法

Student.h

-(id)initWithAge:(int)age;

student.m

-(id)initWithAge:(int)age{

if(self=[super init]){   //如果super返回的对象不为空

_age=age;  

}

return self;

}

----------------------

验证Book对象是否回收

Book.m

-(void)dealloc{

NSLog(@" book:%f 被销毁了",_price);

[super dealloc];

}

----------------------------

//with _price Book constructor

Book.h

-(void)initWithPrice:(float)price;

Book.m

-(void)initWithPrice:(float)price{

if(self=[super init]){   //如果super返回的对象不为空

_price=price;  

}

}

----------------------------

annotation method

1 #pragma mark constructor

(advantage:easy:locate)

2 #pragma mark -groupname

(advantage :group)

3 Of course // can work

----------------------------

main.m

#import "Book.h"

#import "Student.h"

main(){

@autoreleasepool{

Student *stu=[[Student alloc]initWithAge:10]; //stu 1

Book *book =[[Book alloc]initWithPrice:3.5];// book 1

stu.book=book;// In reality never use this way//book 1

[book release];//book 0

[stu release];//stu 0

}

return 0;

}

---------------------------------

Student.m

//manually realize getter & setter

//Standard realization of getter and setter

Student.h   // Because u do manually so XCode will not call  @synthesize, so there is no //_book,so we need to state _book ourself.

@interface Student:NSObject{

Book *_book;

}

Student.m

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

_book=book;

}

-(Book *)book{

return _book;

}

// Abopve six line can be short for 

//@synthesize book=_book;

---------------------------------------

Then counter

-----------------------------------------

// When we developing in reality ,we may use object

//so change code

//main.m

void test (Student *stu){

Book *book=[[Book  alloc]initWithPrice:3.5];

stu.book=book;

[book release];

}

void test1(Student *stu){

//add reading method

//Student.h -(void)readBook;

//Student.m 

//-(void)readBook{

//NSLog(@"Reading book is:%f",_book.price);

//}

[stu readBook];// not safe ,visiting _book,because in test book is released so (wild pointer)

}

-------------------------

//change code

main(){

test(stu);

test1(stu);

}

-----------------------------

//student want to make use of book object so, retain book in Student

//setBook retain;stu alloc release 

 ---------------------------------

//Improve code

// so compare the passed book object  with current book object if not the same one, 

//release the previous one.

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

if(self.book!=book){

[_book release];             // empty pointer is safe.

_book=[book retain];

}

}

//被释放(-1)和被销毁(0)不同

原文地址:https://www.cnblogs.com/yesihoang/p/4487189.html