Obj-C Memory Management

来源:https://www.cnblogs.com/xujinzhong/archive/2018/02/09/8434702.html
-Advertisement-
Play Games

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 whe ...


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 0;
}

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

2013-09-28 04:39:52.310 demo[8385] Hello, World!
2013-09-28 04:39:52.311 demo[8385] Retain Count after initial allocation: 1
2013-09-28 04:39:52.311 demo[8385] Retain Count after retain: 2
2013-09-28 04:39:52.311 demo[8385] Retain Count after release: 1
2013-09-28 04:39:52.311 demo[8385] Object deallocated
2013-09-28 04:39:52.311 demo[8385] 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 0;
}

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

2013-09-28 04:45:47.310 demo[8385] Hello, World!
2013-09-28 04:45:47.311 demo[8385] Object deallocated

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • There may be a situation, when you need to execute a block of code several number of times. In general, statements are executed sequentially: The firs ...
  • 目錄: 一、Viewpager的簡單介紹 二、簡單的Viewpager使用 三、簡單顯示圖片的Viewpager實現 四、廣告圖的實現及Viewpager指示器(小圓點)的實現 五、APP引導頁的實現 一、ViewPager介紹 官方文檔解釋: Layout manager that allows ...
  • 一、核心動畫概念 -導入QuartzCore.framework框架 1⃣ 開發步驟1.初始化一個動畫對象(CAAnimation)並且設置一些動畫相關屬性 2.CALayer中很多屬性都可以通過CAAnimation實現動畫效果,包括:opacity、position、transform、boun ...
  • 翻轉的動畫 旋轉動畫 偏移動畫 翻頁動畫 縮放動畫 取反的動畫效果是根據當前的動畫取他的相反的動畫 ...
  • 前言 剛接手電筒子書項目時,和安卓開發者pt Cai老師【aipiti Cai,一個我很敬佩很資深的開發工程師,設計領域:c++、Java、安卓、QT等】共同商議了一下,因為項目要做要同步,移動端【手機端】和PC【電腦端】的同步問題,讓我們無法決定該用那種方式去呈現電子書,因為PC要展示的電子書有網路 ...
  • 介紹 Runloop是一種事件監聽迴圈,可以理解成一個while死迴圈,監聽到事件就起來,沒有就休息。 Runloop可以在不同模式下進行切換,iOS有五種模式,其中UIInitializationRunLoopModel應用程式啟動時會使用,啟動完成後將不再使用;GSEventReceiveRun ...
  • 首先這應該是一個老生常談的設計了,但是畢竟身為小白的自己都沒動手做過,不動手怎麼提高自己呢,所以在這梅林沉船閑暇之際,我就把我的設計流程與思路記錄下來。首先來看看效果圖吧: 如上圖就是一個簡單並沒有美化過的時鐘,接下來我就來講講我的設計流程與思路。 一.首先繼承view重寫裡面的onDraw方法。 ...
  • 閱讀目錄 一、什麼是記憶體泄露? 二、記憶體泄露的危害 三、解決方案 四、總結 一、什麼是記憶體泄露? Java使用有向圖機制,通過GC自動檢查記憶體中的對象(什麼時候檢查由虛擬機決定),如果GC發現一個或一組對象為不可到達狀態,則將該對象從記憶體中回收。也就是說,一個對象不被任何引用所指向,則該對象會在被G ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...