1.内存管理—黄金法则
The basic rule to apply is Everything that increases the reference counter with alloc,[mutable]copy[withZone:],or retain is in charge of the corresponding [auto]release.
如果对一个对象使用了alloc、[mutable]copy[withZone:]、retain,那么你必须使用相应的release或者autorelease。(如果你让这个对象的引用计数加1,那么当你在使用完成后,需要将对象的引用计数减1)
2.对象的引用计数
(1)每个对象都有自己的引用计数,表示该对象被引用的次数,即有多少人正在同时使用该对象
(2)每个对象内部都有专门的4个字节来存储引用计数器属性
3.对象的深拷贝
(1)任何OC类的对象如果想进行深拷贝都需要遵守NSCoping协议,并实现协议中的方法.
(2)程序举例
Student.h
#import <Foundation/Foundation.h>
@interface Student : NSObject <NSCopying>//遵守这个协议
@property (copy, nonatomic)NSString *name;
- (id)copyWithZone:(NSZone *)zone;
@end
Student.m
#import "Student.h"
@implementation Student
- (id)copyWithZone:(NSZone *)zone{
Student *std = [[Student alloc] init];
std.name = _name;//连同对象中的实例变量一起进行拷贝
return std;
}
@end
4.autoreleasepool和autorelease
(1)autoreleasepool
自动释放池,池子里都是发送了autorelease消息的对象,当自动释放池被销毁时,会对池子中的所有对象发送一个release消息
(1)autorelease
当对象调用autorelease方法时,会把对象扔进最近的autoreleasepool中,将对象由自动释放池管理
5.retain和copy
(1)retain修饰的只是引用计数+1
(2)copy修饰的会先创建一块内存,再进行值拷贝
6.assign/retain和weak/strong
(1)在arc中,使用weak/strong或者assign/retain都可以
(2)而在mrc中,只能使用assign/retain
(3)assign对应weak,retain对应strong