How to Manage Memory in Objective-C

At some point every Cocoa and Cocoa Touch developer has to learn how to manage memory while programming with Objective-C.  Unfortunately, it can be a confusing topic if you’re inexperienced or new to the language and frameworks. After doing my own bit of ramp-up in this area a while ago, I distilled everything I learned into three “brain triggers,” or rules, that I can use to easily remember when and how to use -retain, -release, and -autorelease (the three main methods for managing memory in Objective-C). While somewhat similar to the “memory rules” presented in Apple’s 40-page Memory Management Programming Guide for Cocoa , I’ve found my own “brain triggers” to be easier to remember, and the accompanying notes easier to reference.  To that end, I decided to share the information here in case it’s helpful to anyone else.

A Quick Refresher on Memory Management Concepts

If it’s been awhile since you’ve had to think about memory management, a quick Comp Sci 101 refresher might be helpful. Recall that in an object-oriented programming environment, your program will allocate memory for each object that it creates. Similarly, your program is responsible for deallocating (aka “freeing”) that memory when the object is no longer being used; this allows the operating system to use that memory elsewhere. You have to be careful, though–freeing the memory prematurely will result in a dangling pointer , and conversely, failing to free an object that’s no longer being used causes a memory leak . The big question, then, is how do you know when it’s safe to deallocate an object?

One easy way to solve this problem is to use a technique called “reference counting .” Referencing counting is pretty simple: every object has an internal counter that keep track of how many pointers are, well, pointing to it. As more pointers reference the object, the reference count goes up. When a pointer stops referencing an object the reference count should go down. In other words: if an object’s reference count goes down to zero, you know it’s safe to deallocate it.

Most Objective-C classes inherits the aforementioned reference-counting mechanism from NSObject (a core class provided by the Foundation Framework ). More specifically, nearly all objects have two methods used to increase/decrease the reference count: -retain and -release. Each time an object’s -retain method is called, its reference count is incremented. Conversely, calling an object’s -release method decrements the reference count. If you call -release on an object such that its reference count reaches zero, the -release method will free the memory being used by the object (literally calling the C “free ” function). Finally, you can use the -retainCount method to access an object’s current reference count.

Note: While UIKit / Cocoa Touch applications running on the iPhone must use reference counting as described above, AppKit / Cocoa applications that run in OS X can take advantage of the garbage collection mechanism that was introduced with Objective-C 2.0 in 2006.

Three “Brain Triggers” For Remembering How to Use retain/release/autorelease

Once you understand the concept of reference counting and what NSObject’s -retain and -release methods do, you can start learning how and when to use them. At a high level, the rules of reference counting are as follows:

  1. If you allocate or copy an object , you are responsible for ensuring that it is released via -release or -autorelease.
  2. If someone else allocates an object that you reference for a long time , use -retain/-release to show ownership.
  3. If you add/remove objects to/from a collection , understand that the collection will automatically -retain/-release those objects.

Note that each rule is worded as a conditional statement and that the condition is in bold; these are the “brain triggers” that can be used to help make reference counting easier. The idea of a “brain trigger” is similar to a database trigger. As you’re writing code you should watch for these events to occur (e.g., “Hey, I just allocated an object in a convenience constructor–what am I supposed to do, again? “). This is your cue to take action (”Ah yes, I need to make sure I call -release or -autorelease! “).

Rule #1: If you allocate or copy an object , you are responsible for ensuring that it is released via -release or -autorelease.

When you allocate and initialize an object (or copy it) the object’s reference count is set to 1 for you by default. Because you caused the object’s reference count to be incremented, you are responsible for ensuring that it is also decremented at some point.

Scenario A: Allocating and releasing an object in the same code block

  1. NSString *someStr = [[NSString alloc] initWithString:@ "hello" ];  // ref count 1   
  2. NSString *strCopy = [someStr copy]; // ref count 1   
  3. NSLog(strCopy);  
  4.   
  5. [someStr release]; // Decrement ref count to 0, causes object free itself   
  6. [strCopy release]; // Decrement ref count to 0, causes object free itself   

Scenario B: Allocating in one block, releasing later inside the standard -dealloc method

Sometimes you can’t immediately release an object that you’ve created. If the object is stored as an instance variable, for example, you can release it later in your class’ -dealloc method.

  1. @interface MyClass : NSObject  
  2. {  
  3.     NSString *_myStr;  
  4. }  
  5. @end  
  6.   
  7. @implementation MyClass  
  8.   
  9. -(void ) someMethod  
  10. {  
  11.     [_myStr release];  
  12.     _myStr = [[NSString alloc] initWithString:@"blah" ];  
  13.   
  14.     // Note: We release _myStr first in case this method has already   
  15.     // been called (i.e., an existing _myStr objects exists). Remember   
  16.     // that it's okay to call methods on null objects, so there's no   
  17.     // danger of a null pointer error.   
  18. }  
  19.   
  20. -(void ) dealloc  
  21. {  
  22.     [_myStr release];  
  23.     [super release];  
  24.   
  25.     // Note: If -someMethod is never called, then _myStr will be null.   
  26.     // It's okay to send messages to null objects, however, so calling   
  27.     // release won't cause any problems.   
  28. }  

Scenario C: Allocating objects, “giving them away,” and ensuring they’re released later via autorelease pools

What if your method creates and returns an object without keeping a reference to it? For example, this is a common scenario for “convenience constructor” methods which allocate, initialize, and return objects. Here’s an example:

  1. +(SomeClass *) convenienceConstructor:(NSString *)name  
  2. {  
  3.     SomeClass *someObj = [[SomeClass alloc] init];  
  4.     return  someObj;  
  5. }  

In this situation, the convenience constructor method can’t release the object immediately; that would result in it returning a dangling pointer. Similarly, we’re not storing someObj as an instance variable so we can’t release it inside the object’s -dealloc method. So what do you do? One solution to this problem is to use autorelease pools. At a high level, it works like this:

  1. Ensure that a data structure (e.g., an array) exists outside the scope of the method that is allocating objects. This data structure essentially becomes the “pool of objects that need to be released later.”
  2. Code methods like the above convenience constructor such that they add each newly-created object to the “release later” pool before returning them.
  3. Ensure that all the objects in the “release later” pool are, well, released at some point.

Thankfully, Apple offers a few pre-made tools you can use to implement each step of this mechanism:

  • An NSAutoreleasePool class already exists which you can use as the “release later” pool described in Step 1.
  • Every class that extends NSObject inherits an -autorelease method which implements Step 2 (i.e., automatically adds the object to the “nearest” NSAutoreleasePool instance).
  • To release all the objects in the “release later” pool as described in Step 3, you can use the NSAutoreleasePool’s -drain (or -release) methods.
Note: Autorelease pools can be stacked (some might say “nested”); function A might create an NSAutoreleasePool instance and call function B, which creates another autorelease pool. When an object’s -autorelease method is called, it is added to the “nearest” autorelease pool. And when that pool is released, so are any objects it contains.

The code example below illustrates how you can use autorelease pools

  1. // MainProgram.m   
  2. ...  
  3. -(void ) handleMainButtonClick  
  4. {  
  5.     // Create the auto-release pool for the scope of this method.   
  6.     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];  
  7.   
  8.     // NSNumber is a Foundation Framework class. Note that we don't directly   
  9.     // allocate the NSNumber instance; the -numberWithInt method does   
  10.     // that for us and is therefore responsible for adding the object it allocates   
  11.     // to the nearest NSAutoreleasePool instance (i.e., the one created above).   
  12.     NSNumber *someNum = [NSNumber numberWithInt:123];  
  13.   
  14.     // Again, we aren't directly allocating an instance of our custom   
  15.     // GreetingGenerator class; the -greetingWithName method should take   
  16.     // responsibility for adding it to the nearest NSAutoreleasePool   
  17.     GreetingGenerator *gen = [GreetingGenerator greetingWithName:@"Clint" ];  
  18.   
  19.     // Do stuff...   
  20.   
  21.     [pool release];  
  22.     // Now the objects referenced by 'someNum' and 'gen' will be released when   
  23.     // the thread leaves this block and the autorelease pool is 'popped' off   
  24.     // the stack. Note that you could still call -retain on either of this objects   
  25.     // to prevent that from happening.   
  26. }  
  1. // GreetingGenerator.m   
  2.   
  3. +(GreetingGenerator *) greetingWithName:(NSString *)name  
  4. {  
  5.     GreetingGenerator *generator = [[GreetingGenerator alloc] init];  
  6.     [generator setName:name];  
  7.   
  8.     // We created "generator" and are responsible for ensuring that it is   
  9.     // released. We'll add the object to the nearest NSAutoreleasePool   
  10.     // instance so it can be released later. An instance of NSAutoreleasePool must   
  11.     // have been created before call -autorelease!   
  12.     [generator autorelease];  
  13.   
  14.     return  generator;  
  15. }  

Here’s one final tip regarding autorelease pools. In some situations you may want to drain a pool to clean up memory but prevent specific objects from being deallocated. Simply call -retain on the objects you want to keep (i.e., increment their reference count so that it doesn’t reach 0 when the pool is drained). Here’s a contrived example:

  1. -( void ) someMethod  
  2. {  
  3.     NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];  
  4.   
  5.     NSString *string1 = [NSString stringWithString:@"blah" ];  
  6.     NSString *string2 = [NSString stringWithString:string1];  
  7.   
  8.     // Assume we have an instance variable called _string3   
  9.     _string3 = [NSString stringWithString:string2];  
  10.   
  11.     [_string3 retain];  
  12.   
  13.     [pool release];  
  14.     // string1 and string2 will now be deallocated when the method finishes, but   
  15.     // _string3 will remain since we incremented its ref count.   
  16. }  

Rule #2: If someone else allocates an object for you , use -retain/-release to show ownership.

If your code receives a pointer to an object that it did not create, then you are not responsible for ensuring that it is released. Per Rule #1, the class that creates an object is responsible for ensuring that it is released. But how can you prevent the code this is responsible for this from releasing the object while you’re still using it? Call the object’s -retain method.

Sending the -retain message to an object will cause the its reference count to increment. Once you’re done using the object, however, you must call its -release method to decrement the object’s reference count. This will ensure that the reference count accurately reflects the number of “owners” it has; once all the owners call -release, the count should reach 0 and the object will free itself from memory.

Note: The example code below uses setter methods to illustrate Rule #2. It’s worth mentioning that, in the case of Cocoa development, setter methods often receive objects that were loaded from nib files (especially when building user interfaces). If you don’t really understand how nib files work, you might be wondering if Rule #2 still applies. The quick answer is: yes. Every object loaded from a nib is automatically added to an autorelease pool (i.e., its -autorelase method is called by the nib-loading mechanism). That said, the official Apple documentation regarding Nib files specifically states that if an object is loaded from a nib and passed to a setter method, that setter method should -retain the object. This ensures that it won’t be destroyed while you’re using it, even if the autorelease pool were released.

Scenario A: Hand-coded setter method

  1. -( void ) setImage: (UIImageView *)newImage  
  2. {  
  3.     // We didn't allocate the 'newImage' object so we'll assume that   
  4.     // whoever did was responsible and added it to an autorelease pool.   
  5.     // To ensure that it isn't destroyed while we're using it, we'll   
  6.     // manually call -retain.   
  7.     [newImage retain];  
  8.   
  9.     // Release our old object (may be null, but that's okay)   
  10.     [_myImageView release];   
  11.   
  12.     // Point our instance variable at the object being passed in   
  13.     _myImageView = newImage;  
  14.   
  15.     /* Note: this pattern (i.e., retain the parameter, release the old ivar,  
  16.        then set the ivar to point at the parameter) is great because it also  
  17.        handles scenario in which newImage and _myImageView are both already  
  18.        pointing to the same object. Object's retain count will be inaccurately  
  19.        high when we call [newImage retain], but is immediately lowered to  
  20.        accurate count when we call [_myImageView release] on the next line.  
  21.      */   
  22. }  
  23.   
  24. -(void ) dealloc  
  25. {  
  26.     [_myImageView release]; // We're done using this object   
  27.     [super release];  
  28. }  

Scenario B: Auto-generated setter method

One of the big additions to Objective-C 2.0 is the @property and @synthesize directives, which can be used to automatically generate getter/setter methods for you. It’s important to remember that you still need to use -retain and -release as if you were manually coding a setter method. If you use the “retain” keyword in your @property declaration (as shown below), the generated setter method will essentially do the same thing as the hand-coded one shown above in Example A.

  1. @interface Person : NSObject  
  2. {  
  3.     NSString *_name;  
  4. }  
  5. // This will be converted into a pair of getter/setter methods   
  6. @property (nonatomic, retain) NSString name;  
  7. @end  
  8.   
  9. @implementation Person  
  10.   
  11. // Generate getter/setter methods   
  12. @synthesize name=_name;  
  13.   
  14. -(void ) dealloc  
  15. {  
  16.     // The setter method retained '_name', so now we must release   
  17.     [_name release];  
  18.     [super release];  
  19. }  
  20. @end  

Rule #3: If you add/remove objects to/from a collection , understand that the collection will automatically -retain/-release those objects.

It’s important to be aware of the fact that data structures such as NSMutableArray , NSDictionary , etc., will automatically -retain and -release objects when they are added/removed to and from the collection. Specifically, when you add an object to a collection its reference count is incremented. When you remove an object, the reference count is decremented. Finally, if you release the collection, the objects inside are also released.

Example

  1. NSMutableArray *numberArray = [NSMutableArray arrayWithCapacity:2];  
  2.   
  3. NSNumber *num1 = [NSNumber numberWithInt:333];  
  4. NSNumber *num2 = [NSNumber numberWithInt:777];  
  5. // Both NSNumber instances currently have a reference count of 1   
  6.   
  7. [numberArray addObject: num1];  
  8. [numberArray addObject: num2];  
  9. // Both NSNumber instances currently have a reference count of 2   
  10.   
  11. [num1 release];  
  12. [num2 release];  
  13. // Both NSNumber instances currently have a reference count of 1   
  14.   
  15. // Remove last number from the array ("777")   
  16. NSNumber *lastNumber = [numberArray objectAtIndex:[numberArray count]-1];  
  17. [lastNumber retain]; // "777" instance now has ref count of 2   
  18. [numberArray removeLastObject]; // "777" instance now has ref count of 1   
  19. [lastNumber release]; // Decrements "777" ref count to 0, object frees itself   
  20.   
  21. // Release the array, triggering all objects inside to be released.   
  22. // Specifically, the "333" number instance will have its ref count   
  23. // decremented from 1 to 0, thus causing it to release itself.   
  24. [numberArray release];  

Summary

If all of this leaves you thinking, “Whew, that’s a lot to remember!” don’t worry–the point here is that you don’t need to memorize everything at once. Just memorize the “triggers” (i.e., the three “if” statements):

  1. If you allocate or copy an object , you are responsible for ensuring that it is released via -release or -autorelease.
  2. If someone else allocates an object that you reference for a long time , use -retain/-release to show ownership.
  3. If you add/remove objects to/from a collection , understand that the collection will automatically -retain/-release those objects.

These will at least remind you to look up information on what you need to do.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C语言是一种广泛使用的编程语言,它具有高效、灵活、可移植性强等特点,被广泛应用于操作系统、嵌入式系统、数据库、编译器等领域的开发。C语言的基本语法包括变量、数据类型、运算符、控制结构(如if语句、循环语句等)、函数、指针等。在编写C程序时,需要注意变量的声明和定义、指针的使用、内存的分配与释放等问题。C语言中常用的数据结构包括: 1. 数组:一种存储同类型数据的结构,可以进行索引访问和修改。 2. 链表:一种存储不同类型数据的结构,每个节点包含数据和指向下一个节点的指针。 3. 栈:一种后进先出(LIFO)的数据结构,可以通过压入(push)和弹出(pop)操作进行数据的存储和取出。 4. 队列:一种先进先出(FIFO)的数据结构,可以通过入队(enqueue)和出队(dequeue)操作进行数据的存储和取出。 5. 树:一种存储具有父子关系的数据结构,可以通过中序遍历、前序遍历和后序遍历等方式进行数据的访问和修改。 6. 图:一种存储具有节点和边关系的数据结构,可以通过广度优先搜索、深度优先搜索等方式进行数据的访问和修改。 这些数据结构在C语言中都有相应的实现方式,可以应用于各种不同的场景。C语言中的各种数据结构都有其优缺点,下面列举一些常见的数据结构的优缺点: 数组: 优点:访问和修改元素的速度非常快,适用于需要频繁读取和修改数据的场合。 缺点:数组的长度是固定的,不适合存储大小不固定的动态数据,另外数组在内存中是连续分配的,当数组较大时可能会导致内存碎片化。 链表: 优点:可以方便地插入和删除元素,适用于需要频繁插入和删除数据的场合。 缺点:访问和修改元素的速度相对较慢,因为需要遍历链表找到指定的节点。 栈: 优点:后进先出(LIFO)的特性使得栈在处理递归和括号匹配等问题时非常方便。 缺点:栈的空间有限,当数据量较大时可能会导致栈溢出。 队列: 优点:先进先出(FIFO)的特性使得
C语言是一种广泛使用的编程语言,它具有高效、灵活、可移植性强等特点,被广泛应用于操作系统、嵌入式系统、数据库、编译器等领域的开发。C语言的基本语法包括变量、数据类型、运算符、控制结构(如if语句、循环语句等)、函数、指针等。下面详细介绍C语言的基本概念和语法。 1. 变量和数据类型 在C语言中,变量用于存储数据,数据类型用于定义变量的类型和范围。C语言支持多种数据类型,包括基本数据类型(如int、float、char等)和复合数据类型(如结构体、联合等)。 2. 运算符 C语言中常用的运算符包括算术运算符(如+、、、/等)、关系运算符(如==、!=、、=、<、<=等)、逻辑运算符(如&&、||、!等)。此外,还有位运算符(如&、|、^等)和指针运算符(如、等)。 3. 控制结构 C语言中常用的控制结构包括if语句、循环语句(如for、while等)和switch语句。通过这些控制结构,可以实现程序的分支、循环和多路选择等功能。 4. 函数 函数是C语言中用于封装代码的单元,可以实现代码的复用和模块化。C语言中定义函数使用关键字“void”或返回值类型(如int、float等),并通过“{”和“}”括起来的代码块来实现函数的功能。 5. 指针 指针是C语言中用于存储变量地址的变量。通过指针,可以实现对内存的间接访问和修改。C语言中定义指针使用星号()符号,指向数组、字符串和结构体等数据结构时,还需要注意数组名和字符串常量的特殊性质。 6. 数组和字符串 数组是C语言中用于存储同类型数据的结构,可以通过索引访问和修改数组中的元素。字符串是C语言中用于存储文本数据的特殊类型,通常以字符串常量的形式出现,用双引号("...")括起来,末尾自动添加'\0'字符。 7. 结构体和联合 结构体和联合是C语言中用于存储不同类型数据的复合数据类型。结构体由多个成员组成,每个成员可以是不同的数据类型;联合由多个变量组成,它们共用同一块内存空间。通过结构体和联合,可以实现数据的封装和抽象。 8. 文件操作 C语言中通过文件操作函数(如fopen、fclose、fread、fwrite等)实现对文件的读写操作。文件操作函数通常返回文件指针,用于表示打开的文件。通过文件指针,可以进行文件的定位、读写等操作。 总之,C语言是一种功能强大、灵活高效的编程语言,广泛应用于各种领域。掌握C语言的基本语法和数据结构,可以为编程学习和实践打下坚实的基础。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值