回顾
malloc free
JAVA C# GC Garbage collection 垃圾回收机制
mac os
ARC Automatic Reference Count 自动引用计数
MRC Manual Reference Count 手动管理内存
引用计数
引用:强引用/弱引用
弱引用:assign
引用计数
# 手动内存管理(Manual Reference Counting)(应用非常灵活)MRC
ARC (Automatic Reference Counting)
堆空间 :
1.忘记释放 —> 内存泄露
2.提前/过早释放 ---> 内存崩溃
3.多释放 —> 崩溃 C野指针
malloc free free
内存管理 管理的是堆空间
谁来释放?程序员负责释放
# 内存管理原理
# c模拟
# retain release dealloc
# new
# setter方法中的内存注意事项
# 不要管太多,管好自己 黄金法则
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
NSMutableString *str1 = nil;
NSMutableString *str2 = nil;
@autoreleasepool {
str1 = [[NSMutableString alloc] initWithString:@"Welcome to beijing"];
str2 = [NSMutableString stringWithString:@"Welcome to zhenzhou"];
NSLog(@"%@ %ld", str1, str1.retainCount);
NSLog(@"%@ %ld", str2, str2.retainCount);
}
NSLog(@"-------------------------");
[str1 setString:@"Respect China"];
[str1 release];
[str1 release];
NSLog(@"%@ %ld", str1, str1.retainCount);
//[str2 release];
//NSLog(@"%@ %ld", str2, str2.retainCount);
return 0;
}
# 字符串的copy/mutableCopy
注:
Dog *dog2 = [dog1 copy];
在使用copy /mutableCopy的时候 ,使用的对象所属的类必须要遵守协议NSCopying /NSMutableCopying协议,实现里面的方法。
因为在执行copy函数的时候,内部会调用当前对象的copyWithZone:方法, 所以使用copy前 必须要遵守协议实现copyWithZone:方法
NSString NSArray NSDictionary 这些类都遵守了拷贝协议 实现了里面的方法,可以直接用copy 。可以字符串对象常常用拷贝函数
# dealloc
# 内存管理之属性要注意的地方
# autorelease和自动释放池
# 数组/字典的内存管理