黑马程序员-oc中内存管理的相关知识

------- android培训java培训、期待与您交流! ----------


一、理论派



1.任何继承字NSObject的对象,都需要手动来管理内存


2.每一个对象内部都有一个整数,成为引用计数。当引用计数器为0时,回收


3.当使用alloc、new、copy船舰一个对象时,计数器被设置为1


4.给一个对象发送一条消息-》retain,计数器+1


5.给一个对象发送一条消息-》release,计数器值-1


6.当计数器值为0时,会调用delloc方法,通常我们重写这个方法,在里面释放一些资源


7.通过给对象发送retainCount消息,可以获取当前对象的引用计数值


二、实例


Book.h文件


复制代码
//
//  Student.h
//  内存管理
//
//  Created by apple on 14-3-26.
//  Copyright (c) 2014年 apple. All rights reserved.
//


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


@interface Student : NSObject
{
    int _age;
    Book *_book;
}


@property int age;
@property Book *book;


@end
复制代码
Book.m文件


复制代码
//
//  Book.m
//  内存管理
//
//  Created by apple on 14-3-26.
//  Copyright (c) 2014年 apple. All rights reserved.
//


#import "Book.h"


@implementation Book


- (NSString *)description
{
    return [NSString stringWithFormat:@"the price is %0.2f", _price];
}


-(void)dealloc
{
    NSLog(@"%@被销毁", self);
    
    [super dealloc];
}


@end
复制代码
 


Student.h文件


复制代码
//
//  Student.h
//  内存管理
//
//  Created by apple on 14-3-26.
//  Copyright (c) 2014年 apple. All rights reserved.
//


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


@interface Student : NSObject
{
    int _age;
    Book *_book;
}


@property int age;
@property Book *book;


@end
复制代码
 


Student.m文件 Student.m


复制代码
//  内存管理
//
//  Created by apple on 14-3-26.
//  Copyright (c) 2014年 apple. All rights reserved.
//


#import "Student.h"


@implementation Student




-(void)setBook:(int *)book
{
    if (_book != book) {


        [_book release];
     _book = [book retain];
    }
}


-(void)dealloc
{
    NSLog(@"%@被销毁", self);
    [_book release];
    [super dealloc];
}


-(NSString *)description
{
    NSString *str = [NSString stringWithFormat:@"age is %i",self.age];
    
    return str;
}


@end
复制代码
 


main.m文件


复制代码
//
//  main.m
//  内存管理
//
//  Created by apple on 14-3-26.
//  Copyright (c) 2014年 apple. All rights reserved.
//


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


int main(int argc, const char * argv[])
{


    @autoreleasepool {
        
        Student *stu = [[Student alloc]init];
        stu.age = 10;
        
        Book *book1 = [[Book alloc]init];
        book1.price = 3.7;
        
        Book *book2 = [[Book alloc]init];
        book2.price = 4.7;
        
        stu.book = book1;
        stu.book = book2;
        
        [book1 release];
        [book2 release];
        [stu release];
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值