内存管理(1)

来源:互联网 发布:一楼土木人淘宝网 编辑:程序博客网 时间:2024/05/17 08:51
内存管理

黄金法则:The basic to apply to 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。

基本类型 (任何C的类型)如:int,long,long long,struct等。
内存管理对于C语言基本类型无效。
OC类型 (非基本类型)
任何继承于NSObject类型的对象属于OC类型,也就是除了C的任何类型。
所有的OC类型对象都有一个叫retainCount的变量,叫做计数器,用于保存当前被引用的数量。如果计数为零,就真正释放这个对象。

alloc函数是创建对象使用,创建完成后计数器为1,只用一次。
retain函数是对一个计数器加1,可以使用多次。如果需要引用对象就可以向对象发送retain消息。
release函数是对计数器减1,当计数器减到0时,对象就会自动调用dealloc函数,从内存中释放。如果不需要引用对象,可以给对象发送release消息。并且,计数器为0的对象,不能再使用release和其他方法。

遛狗原理
Person.h
#import “Foundation/Foundation.h"
#import “Dog.h"
@interface Person: NSObject
{
     Dog * _dog;
}
- (void) setDog: (Dog *) aDog;
- (Dog *) dog;
@end

Person.m
@implemation Person
- (void) dealloc
{
     [_dog release];
     [super dealloc];
}
- (Dog *) dog
{
     return _dog;
}
- (void) setDog: (Dog *) aDog
{
     if (_dog != aDog)
     {
          [_dog release];
          _dog = [aDog retain];//让计数器加1
     }
}
@end

Dog.h
@interface Dog: NSObject
{
     int _ID;
}
@property int ID;
@end

Dog.m
@implemation Dog
@synthesize ID = _ID;
- (void) dealloc
{
     [super dealloc];
}
@end

main.m
#import “Foundation/Foundation.h”
int mian ()
{
     @autoreleasepool{
               Dog *dog1 = [[Dog alloc] init];
               [dog1 setID:1];
               Person *xiaoli = [[Person alloc] init];
               [xiaoli setDog: dog1];
               NSLog(@“dog1 retain count is %ld”, [dog1 retainCount]);
               [dog1 release];
               NSLog(@“dog1 retain count2 is %ld”, [dog1 retainCount]);//dog1虽然release但是仍然可以                                                      使用,因为dog1的对象还在。
               [xiaoli release];
               NSLog(@“dog1 retain count3 is %ld”, [dog1 retainCount]);
         }      {
}
0 0