打开Xcode,新建Command Line Tool工程(Type选择Foundation),直到完成;
在工程下新建文件:Book和Person;
Book.m
#import "Book.h"
@implementation Book
- (void)setPrice:(int)price
{
_price = price;
}
- (int)price
{
return _price;
}
- (void)dealloc
{
NSLog(@"Book对象被回收");
[super dealloc];
}
@end
Person.m
#import "Person.h"
@implementation Person
- (void)setBook:(Book *)book
{
_book = [book retain];
}
- (Book *)book
{
return _book;
}
- (void)dealloc
{
[_book release];
NSLog(@"Person对象被回收");
[super dealloc];
}
@end
main.m
#import <Foundation/Foundation.h>
#import "Person.h"
#import "Book.h"
int main(int argc, const char * argv[])
{
Book *b = [[Book alloc] init];
Person *p1 = [[Person alloc] init];
[p1 setBook:b];
[b release];
b = nil;
[p1 release];
p1 = nil;
return 0;
}
Book.h和Person.h自己根据.m添加完整。
编译并运行:
2014-10-30 23:10:28.022 02-多个对象的内存管理[991:303] Book对象被回收
2014-10-30 23:10:28.024 02-多个对象的内存管理[991:303] Person对象被回收
Program ended with exit code: 0
object-c内存管理原则:
谁创建,谁release;
谁retain,谁release;
使用时引用计数器加一(retain或alloc/new),释放时计数器减一;
注:
Xcode默认ARC是 ON 的状态,这些代码编译不过,需要修改项目的编译设置:“Objectice-C Auto Reference Counteting”设为NO。