@interface Book : NSObject
{
int _price;
}
- (void)setPrice:(int)price;
- (int)price;
@end
#import "Book.h"
@implementation Book
- (void)setPrice:(int)price
{
_price = price;
}
- (int)price
{
return _price;
}
- (void)dealloc
{
NSLog(@"Book对象被回收");
[super dealloc];
}
@end
#import <Foundation/Foundation.h>
#import "Book.h"
@interface Person : NSObject
{
Book *_book;
}
- (void)setBook:(Book *)book;
- (Book *)book;
@end
#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
/*
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;
}