Memory management is one of the most important process in any programming language. It is the process by which the memory of objects are allocated when they are required and deallocated when they are no longer required.

Managing object memory is a matter of performance; if an application doesn't free unneeded objects, its memory footprint grows and performance suffers.

Objective-C Memory management techniques can be broadly classified into two types.

  • "Manual Retain-Release" or MRR
  • "Automatic Reference Counting" or ARC

"Manual Retain-Release" or MRR
In MRR, we explicitly manage memory by keeping track of objects on our own. This is implemented using a model, known as reference counting, that the Foundation class NSObject provides in conjunction with the runtime environment.

The only difference between MRR and ARC is that the retain and release is handled by us manually in former while its automatically taken care of in the latter.

The following figure represents an example of how memory management work in Objective-C.

The memory life cycle of the Class A object is shown in the above figure. As you can see, the retain count is shown below the object, when the retain count of an object becomes 0, the object is freed completely and its memory is deallocated for other objects to use.

Class A object is first created using alloc/init method available in NSObject. Now, the retain count becomes 1.

Now, class B retains the Class A's Object and the retain count of Class A's object becomes 2.

Then, Class C makes a copy of the object. Now, it is created as another instance of Class A with same values for the instance variables. Here, the retain count is 1 and not the retain count of the original object. This is represented by the dotted line in the figure.

The copied object is released by Class C using the release method and the retain count becomes 0 and hence the object is destroyed.

In case of the initial Class A Object, the retain count is 2 and it has to be released twice in order for it to be destroyed. This is done by release statements of Class A and Class B which decrements the retain count to 1 and 0, respectively. Finally, the object is destroyed.

MRR Basic Rules
We own any object we create: We create an object using a method whose name begins with "alloc", "new", "copy", or "mutableCopy"

We can take ownership of an object using retain: A received object is normally guaranteed to remain valid within the method it was received in, and that method may also safely return the object to its invoker. We use retain in two situations:

In the implementation of an accessor method or an init method, to take ownership of an object we want to store as a property value.

To prevent an object from being invalidated as a side-effect of some other operation.

When we no longer need it, we must relinquish ownership of an object we own: We relinquish ownership of an object by sending it a release message or an autorelease message. In Cocoa terminology, relinquishing ownership of an object is therefore typically referred to as "releasing" an object.

You must not relinquish ownership of an object you do not own: This is just corollary of the previous policy rules stated explicitly.

#import <Foundation/Foundation.h>

@interface SampleClass:NSObject
- (void)sampleMethod;
@end @implementation SampleClass - (void)sampleMethod
{
NSLog(@"Hello, World! \n");
} - (void)dealloc
{
NSLog(@"Object deallocated");
[super dealloc];
} @end int main()
{
/* my first program in Objective-C */
SampleClass *sampleClass = [[SampleClass alloc]init];
[sampleClass sampleMethod];
NSLog(@"Retain Count after initial allocation: %d",
[sampleClass retainCount]);
[sampleClass retain];
NSLog(@"Retain Count after retain: %d", [sampleClass retainCount]);
[sampleClass release];
NSLog(@"Retain Count after release: %d", [sampleClass retainCount]);
[sampleClass release];
NSLog(@"SampleClass dealloc will be called before this");
// Should set the object to nil
sampleClass = nil;
return ;
}

When we compile the above program, we will get the following output.

-- ::52.310 demo[] Hello, World!
-- ::52.311 demo[] Retain Count after initial allocation:
-- ::52.311 demo[] Retain Count after retain:
-- ::52.311 demo[] Retain Count after release:
-- ::52.311 demo[] Object deallocated
-- ::52.311 demo[] SampleClass dealloc will be called before this

"Automatic Reference Counting" or ARC

In Automatic Reference Counting or ARC, the system uses the same reference counting system as MRR, but it inserts the appropriate memory management method calls for us at compile-time. We are strongly encouraged to use ARC for new projects. If we use ARC, there is typically no need to understand the underlying implementation described in this document, although it may in some situations be helpful. For more about ARC, see Transitioning to ARC Release Notes.

As mentioned above, in ARC, we need not add release and retain methods since that will be taken care by the compiler. Actually, the underlying process of Objective-C is still the same. It uses the retain and release operations internally making it easier for the developer to code without worrying about these operations, which will reduce both the amount of code written and the possibility of memory leaks.

There was another principle called garbage collection, which is used in Mac OS-X along with MRR, but since its deprecation in OS-X Mountain Lion, it has not been discussed along with MRR. Also, iOS objects never had garbage collection feature. And with ARC, there is no use of garbage collection in OS-X too.

Here is a simple ARC example. Note this won't work on online compiler since it does not support ARC.

#import <Foundation/Foundation.h>

@interface SampleClass:NSObject
- (void)sampleMethod;
@end @implementation SampleClass - (void)sampleMethod
{
NSLog(@"Hello, World! \n");
} - (void)dealloc
{
NSLog(@"Object deallocated");
} @end int main()
{
/* my first program in Objective-C */
@autoreleasepool{
SampleClass *sampleClass = [[SampleClass alloc]init];
[sampleClass sampleMethod];
sampleClass = nil;
}
return ;
}

When we compile the above program, we will get the following output.

-- ::47.310 demo[] Hello, World!
-- ::47.311 demo[] Object deallocated

Obj-C Memory Management的更多相关文章

  1. Memory Management in Open Cascade

    Open Cascade中的内存管理 Memory Management in Open Cascade eryar@163.com 一.C++中的内存管理 Memory Management in ...

  2. Java (JVM) Memory Model – Memory Management in Java

    原文地址:http://www.journaldev.com/2856/java-jvm-memory-model-memory-management-in-java Understanding JV ...

  3. Objective-C Memory Management

    Objective-C Memory Management Using Reference Counting 每一个从NSObject派生的对象都继承了对应的内存管理的行为.这些类的内部存在一个称为r ...

  4. Operating System Memory Management、Page Fault Exception、Cache Replacement Strategy Learning、LRU Algorithm

    目录 . 引言 . 页表 . 结构化内存管理 . 物理内存的管理 . SLAB分配器 . 处理器高速缓存和TLB控制 . 内存管理的概念 . 内存覆盖与内存交换 . 内存连续分配管理方式 . 内存非连 ...

  5. Android内存管理(2)HUNTING YOUR LEAKS: MEMORY MANAGEMENT IN ANDROID PART 2

    from: http://www.raizlabs.com/dev/2014/04/hunting-your-leaks-memory-management-in-android-part-2-of- ...

  6. Android内存管理(1)WRANGLING DALVIK: MEMORY MANAGEMENT IN ANDROID PART 1

    from : http://www.raizlabs.com/dev/2014/03/wrangling-dalvik-memory-management-in-android-part-1-of-2 ...

  7. Understanding Memory Management(2)

    Understanding Memory Management Memory management is the process of allocating new objects and remov ...

  8. Java Memory Management(1)

    Java Memory Management, with its built-in garbage collection, is one of the language’s finest achiev ...

  9. ural1037 Memory Management

    Memory Management Time limit: 2.0 secondMemory limit: 64 MB Background Don't you know that at school ...

  10. 再谈.net的堆和栈---.NET Memory Management Basics

    .NET Memory Management Basics .NET memory management is designed so that the programmer is freed fro ...

随机推荐

  1. python BaseManager分布式学习

    如果我们已经有一个通过Queue通信的多进程程序在同一台机器上运行,现在,由于处理任务的进程任务繁重,希望把发送任务的进程和处理任务的进程分布到两台机器上.怎么用分布式进程实现?原有的Queue可以继 ...

  2. Docker运行MongoDB及Redis及ssh端口映射远程连接

    Docker运行MongoDB及Redis及ssh端口映射远程连接 本节内容简介 在本实验里我们将通过完成 MongoDB 和 Redis 两个容器来学习Dockerfile及Docker的运行机制. ...

  3. 二、mysql安装详解

    step1:打开下载的mysql安装文件(mysql-5.5.36-win32.msi),双击运行,如下图: step2:点击“Next”按钮继续,如下图: step3:点击“勾选”,点击“Next” ...

  4. 面试题:sql数据查询

    前几天参加一个面试,面试公司让做一套题,sql题不是很难,但是我第一次还是写错了,回来后,重新写了下.简单记录下吧, 1.题目: 2.测试数据 select * from student ; inse ...

  5. STL树

    前几天觉得STL中没有树和图真是一种莫大的遗憾啊,但是在网上搜了搜,发现其实可以用容器很简单的构造树. 还是废话少说上代码: struct TreeNode{ DataType data; // Da ...

  6. HTML学习笔记(三)样式CSS

    1.样式 外部样式表(通过css文件定义样式,整体样式) 当样式需要被应用到很多页面的时候,使用外部样式表,在 head 部分<link>. <head> <link r ...

  7. 洛谷 - P3966 - 单词 - AC自动机

    https://www.luogu.org/problemnew/show/P3966 因为文本串就是字典本身,所以这个和平时的AC自动机不太一样.平时的query要沿着fail树把子树的出现次数依次 ...

  8. 剖析JSONP原理的小例子

    1. 服务器端代码(Node.js) // 导入 http 内置模块 const http = require('http'); // 这个核心模块,能够帮我们解析 URL地址,从而拿到 pathna ...

  9. css之BFC(block formmatting context)[格式化上下文]

    一.定义: BFC就是一个黑盒子,可以保证盒子内部元素不管如何变化,都不会影响盒子附近的元素:它属于普通流.浮动.定位方案中的普通流. 二.触发条件: 1.body: 2.float(不包含none) ...

  10. 计算机网络自顶向下方法第2章-应用层(application-layer).1

    2.1 应用层协议原理 2.1.1网络应用程序体系结构 1)在客户-服务器体系结构 (client-server architecture)中,有一个总是打开的主机称为服务器,它服务于来自许多其他称为 ...