Objective-c内存管理

前言:在OC语言中,我们大多数时候需要手动去管理内存,来避免内存泄漏,导致系统不可用


内存管理的原理

从Xcode4.2版本开始,xocde引入了ARC(引用计数器)机制,程序在编译时,会自动为代码加入释放代码,因为如果我们手动来管理内存,那么我们必须手动关闭ARC,这样才可以在代码进行 dealloc 处理。

OC中引用计数器机制:OC中每一个对象被创建后都有一个引用计数器的数值(retainCount)同之对应,我们将这个值称之为“引用计数器”,
当一个对象被创建后,retainCount的值变为1
当调用这个对象的 alloc retain new copy方法之后,计数器retainCount会在原来的基础上加1
当调用这个对象的release方法后,计数器retainCount的值会在原来的基础上减1
当retainCount的值为0时,则系统会自动调用当前对象的dealloc方法来销毁这个对象

例test类

//
//  test.h
//  test
//
//  Created by shenye on 16/1/25.
 #import < Foundation / Foundation.h >
 @interface test : NSObject
 #pragma mark --测试属性
 @property(nonatomic,copy)   NSString *info1;
 @property(nonatomic,assign) NSString *info2;
 @end

//  test.m
//  test
//
#import "test.h"
@implementation test

#pragma mark -重写 dealloc

-(void)dealloc{
    NSLog(@"test调用dealloc方法");
    [super dealloc];
}

@end




//
//  main.m
//  test
//
//  Created by shenye on 16/1/25.
//  Copyright © 2016年 com.dchmcl.com. All rights reserved.
//

#import < Foundation / Foundation.h  >

#import "test.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...
        NSLog(@"程序开始执行");
        
        test *t = [[test alloc] init];
        t.info1 =@"测试信息1";
        t.info2 =@"测试信息2";
        
        [t retain];
        NSLog(@"1 retainCount:%lu", (unsigned long)[t retainCount]);
        
        [t retain];
        NSLog(@"2 retainCount:%lu", (unsigned long)[t retainCount]);
        
        
        [t retain];
        NSLog(@"3 retainCount:%lu", (unsigned long)[t retainCount]);
        
        
        [t release];
        NSLog(@"4 retainCount:%lu", (unsigned long)[t retainCount]);

        [t release];
        NSLog(@"5 retainCount:%lu", (unsigned long)[t retainCount]);
        
        
        NSLog(@"类信息:%@ %@", [t info1] ,[t info2]);
        
        
        [t release];
        NSLog(@"6 retainCount:%lu", (unsigned long)[t retainCount]);
        
        
        [t release];
        NSLog(@"7 retainCount:%lu", (unsigned long)[t retainCount]);
        
        
        t.info2 =nil;
        t.info1 =nil;
        t =nil;
        
        
        
    }
    return 0;
}




——–运行结果:

2016-01-25 11:20:01.136 test[5927:416277] 程序开始执行
2016-01-25 11:20:01.137 test[5927:416277] 1 retainCount:2
2016-01-25 11:20:01.137 test[5927:416277] 2 retainCount:3
2016-01-25 11:20:01.138 test[5927:416277] 3 retainCount:4
2016-01-25 11:20:01.138 test[5927:416277] 4 retainCount:3
2016-01-25 11:20:01.138 test[5927:416277] 5 retainCount:2
2016-01-25 11:20:01.138 test[5927:416277] 类信息:测试信息1 测试信息2
2016-01-25 11:20:01.138 test[5927:416277] 6 retainCount:1
2016-01-25 11:20:01.139 test[5927:416277] test调用dealloc方法
2016-01-25 11:20:01.139 test[5927:416277] 7 retainCount:1
Program ended with exit code: 0

以上就是手动释放和保持对象对占用的内存