不好,不推荐学习~~
1、堆和栈
/*
栈:局部变量,定义在方法或函数内部变量
系统管理
堆:动态存储区,OC中的对象
一般由程序员管理
*/
#import <Foundation/Foundation.h>
#import "CZPerson.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
//指针放在栈中,指针所指向对象放在堆中
CZPerson *person = [[CZPerson alloc] init];
}
return 0;
}
2、内存管理
如果内存管理不当
1)不再使用的对象没有被回收,内存泄露,最终导致程序闪退
2)正在被使用的对象被释放了(引用计数为0),野指针,访问野指针就会导致程序奔溃
引用计数
ARC Automatic Reference Counting 自动引用计数
MRC Manual Refernce Counting 手动引用计数
1)当一个对象刚刚出生时,它的引用计数为1
2)当对象上引用计数是0的时候,系统会自动调用dealloc方法,立即把它回收
3)release 引用计数减一
4)retain 引用计数加一
int main(int argc, const char * argv[]) {
CZPerson *person = [[CZPerson alloc] init];
long count = [person retainCount];
NSLog(@"%ld",count);//1
[person retain];//加一
count = [person retainCount];
NSLog(@"%ld",count);//2
[person release];//减一
count = [person retainCount];
NSLog(@"%ld",count);//1
[person release];//减一,引用计数为0,系统自动调用dealloc方法
person = nil;//当一个指针指向nil,称为空指针
//给空指针发送消息系统不会报错,它什么都不做
count = [person retainCount];
NSLog(@"%ld",count);//0
return 0;
}
重写dealloc方法
//永远不要试图自己调用这个方法dealloc
//这个方法是由系统调用的
-(void) dealloc
{
//引用计数为0,验证对象是否被回收了
NSLog(@"要死啦要死啦");
//这个方法中必须调用父类该方法,并且必须放在最后
[super dealloc];
}