首页 > 代码库 > Objective-C的内存管理

Objective-C的内存管理

原则

 内存管理原则:
 1.谁使的引用计数增加,那他也要负责对应的引用计数减少(类似C++,谁new谁delete)
 2.可以对nil的对象release(类似c++允许delete的对象为NULL一样)
 3.当对象引用计数为0时,系统会自动释放该内存
 4.可以借用C++内存管理的经验来控制Objective-C的内存管理
 
  • MemoryDemo.h
     1 //  MemoryDemo.h 2 //  MemoryTest 3 // 4 //  Created by arbboter on 14/11/28. 5 //  Copyright (c) 2014??? arbboter. All rights reserved. 6 // 7  8 #import <Foundation/Foundation.h> 9 10 @interface MemoryDemo : NSObject11 {12     NSString*       _objectName;13     int             _objectCount;14 }15 16 -(void)setObjectName:(NSString*)name;17 -(NSString*)getObjectName;18 19 -(void)setObjectCount:(int)count;20 -(int)getObjectCount;21 22 -(void)showInfo;23 24 -(void)dealloc;

     

  • MemoryDemo.m

     1 // 2 //  MemoryDemo.m 3 //  MemoryTest 4 // 5 //  Created by arbboter on 14/11/28. 6 //  Copyright (c) 2014年 arbboter. All rights reserved. 7 // 8  9 #import "MemoryDemo.h"10 11 @implementation MemoryDemo12 13 -(void)setObjectName:(NSString*)name14 {15     /* 对象重复不予重置 */16     if (name != _objectName)17     {18 #if 119         /* 标准做法 */20         [name retain];21         [_objectName release];22         _objectName = [[NSString alloc] initWithString:name];23         [name release];24 #else25         /* 另一种思路,没想到会出什么问题 */26         [_objectName  release];27         _objectName = [name retain];28 #endif29         30     }31 }32 33 -(NSString*)getObjectName34 {35     return _objectName;36 }37 38 -(void)setObjectCount:(int)count39 {40     _objectCount = count;41 }42 -(int)getObjectCount43 {44     return _objectCount;45 }46 -(void)showInfo47 {48     NSLog(@"name = %@, count = %d", [self getObjectName], [self getObjectCount]);49 }50 51 -(void)dealloc52 {53     [_objectName release];54     [super dealloc];55 }56 57 @end

     

  • main.m

     1 // 2 //  main.m 3 //  MemoryTest 4 // 5 //  Created by arbboter on 14/11/28. 6 //  Copyright (c) 2014年 arbboter. All rights reserved. 7 // 8  9 #import <Foundation/Foundation.h>10 #import "MemoryDemo.h"11 int main(int argc, const char * argv[])12 {13     NSString* name = [[NSString alloc] initWithString:@"Man of pig‘s feet"];14     NSString* nullName = nil;15     MemoryDemo* mem = [[MemoryDemo alloc] init];16     17     /* nil 允许retian,也允许release */18     [nullName retain];19     [mem setObjectName:name];20     [mem setObjectCount:18];21     [mem showInfo];22     23     // release24     [name release];25     /* nil 允许retian,也允许release */26     [nullName release];27     28     // OK!29     [mem showInfo];30     31     [mem release];32 33 #if 034     /* error, mem‘s value is not nil but35      * mem‘s retain count alreadly to be 036      */37     [mem release];38 #endif39     40     return 0;41 }42 43 /**44  * 内存管理原则:45  * 1.谁使的引用计数增加,那他也要负责对应的引用计数减少(类似C++,谁new谁delete)46  * 2.可以对nil的对象release(类似c++允许delete的对象为NULL一样)47  * 3.当对象引用计数为0时,系统会自动释放该内存48  * 4.可以借用C++内存管理的经验来控制Objective-C的内存管理49  */

     

Objective-C的内存管理