黑马程序员22——OC之内存管理(多个对象之间的内存管理)

#import


@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
#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
#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;
}

你可能感兴趣的:(黑马)