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