内存计数基础原理

 

有new、alloc、copy(计数器加一),就得release(计数器减一)

 

 

//
//  Person.h
//  a1
//
//  Created by mahongmin on 14-4-21.
//  Copyright (c) 2014年 mahongmin. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "Book.h"

@interface Person : NSObject
{
    Book *_book;
}

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

@end



================


//
//  Person.m
//  a1
//
//  Created by mahongmin on 14-4-21.
//  Copyright (c) 2014年 mahongmin. All rights reserved.
//

#import "Person.h"

@implementation Person


- (void) setBook:(Book*)book
{
    if (book != _book)// 防止p.book = b; 再来一次p.book = b
    {
        [_book release];// 此场景:如果p.book = b1,然后p.book = b2 那么,就需要此行来把b1 release掉。
        
        _book = [book retain];// book传递进来,那么等于Person对book进行了一次占用 内存占用+1
    }
}

- (Book*) book
{
    return _book;
}

-(void)dealloc
{
    // 当销毁人的时候,需把人占用的book也销毁
    [_book release];
    
    NSLog(@"释放人对象");
    [super dealloc];
}

@end
======================
//
//  Book.h
//  a1
//
//  Created by mahongmin on 14-4-23.
//  Copyright (c) 2014年 mahongmin. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface Book : NSObject

@end


===========================
//
//  Book.m
//  a1
//
//  Created by mahongmin on 14-4-23.
//  Copyright (c) 2014年 mahongmin. All rights reserved.
//

#import "Book.h"

@implementation Book

- (void) dealloc
{
    NSLog(@"释放book对象");
    [super dealloc];
}

@end


====================================
//
//  main.m
//  a1
//
//  Created by mahongmin on 14-4-21.
//  Copyright (c) 2014年 mahongmin. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "Person.h"
#import "Book.h"

int main(int argc, const char * argv[])
{
    Person *p = [[Person alloc] init];
    
    Book *b = [[Book alloc] init];
    
    p.book = b;//此时,b指针指向的Book,计数为2
    
    [b release];
    b = nil;
    [p release];// 如果多次乱调[r release],写了p=nil后,此处不会再报EXC_BAD_ACCESS野指针错误。此时p为空对象,给空对象发送消息,不会产生空指针错误。跟java不一样
    p = nil;
    return 0;
}

 

 

你可能感兴趣的:(内存)