代码改变世界

OC内存管理

2015-12-13 16:33  AB小博客  阅读(161)  评论(0)    收藏  举报

alloc 分配内存

dealloc 释放内存

new分配内存(不常用)init

copy分配内存 (拷贝内容 非地址)

 

retain 引用计数自动加1

release 引用计数自动减1

autorelease自动释放内存

retainCount保留计数值

 

//
//  main.m


#import <Foundation/Foundation.h>
@interface Animal : NSObject 
-(void)showMsg;
@end

@implementation Animal
-(void)showMsg{
    NSLog(@"我是哈哈");
}
-(void)dealloc{   //当减到0的时候执行
    NSLog(@"释放了");
    [super dealloc];
}

@end
int main(int argc, const char * argv[]) {
    @autoreleasepool {
   
        Animal *a = [[Animal alloc]init];//alloc+1
        NSUInteger count = [a retainCount];
        NSLog(@"%lu",count);
        
        [a retain];                     //+1
        NSUInteger count1 = [a retainCount];
        NSLog(@"%lu",count1);
        
        [a release];                    //-1
        NSUInteger count2 = [a retainCount];
        NSLog(@"%lu",count2);
     
        [a release];                    //-1
        NSUInteger count3 = [a retainCount];
        NSLog(@"%lu",count3);
  
    }
    return 0;
}