microleo的个人博客

iOS多个对象之间的内存管理

1.你想使用(占用)某个对象,就应该让对象的计数器+1(让对象做一次retain操作)

2.你不想再使用(占用)某个对象,就应该让对象的计数器-1(让对象做一次release)

3.谁retain,谁release

4.谁alloc,谁release

#import <Foundation/Foundation.h>
#import "Person.h"
#import "Book.h"
int main()
{
// b-1
Book *b = [[Book alloc] init];
// p-1
Person *p1 = [[Person alloc] init];
//p1想占用b这本书
// b-2
[p1 setBook:b];
// p-0
// b-1
[p1 release];
p1 = nil;
// b-0
[b release];
b = nil;
return 0;
}
---Book.m
@implementation Book
- (void)setPrice:(int)price
{
_price = price;
}
- (int)price
{
return _price;
}
- (void)dealloc
{
NSLog(@"Book对象被回收");
[super dealloc];
}
@end
---Person.m
@implementation Person
- (void)setBook:(Book *)book
{
_book = [book retain];
}
- (Book *)book
{
return _book;
}
- (void)dealloc
{
[_book release];
NSLog(@"Person对象被回收");
[super dealloc];
}
@end