iOS 的內存管理和 Windows 有什麼區別?


既然問題問的是 iOS,並且是和 Windows 做對比。那麼就是操作系統層次的內存管理,而不是應用程序層次的堆動態管理。所有關於引用計數的答案都是不切題的。在 Windows 上的 Objective-C(雖然用的很少)也是引用計數的。引用計數和語言和庫有關,和操作系統無關。

更新:iOS 有虛擬內存。也就是應用程序使用的地址要經過 MMU [1] 的翻譯變成物理地址。和 Windows 不同的是 iOS 沒有 paging out,可讀寫的內存不會被交換到 disk。但是對於 read-only 數據,iOS 還是利用了 paging-in-on-demond 機制,和桌面系統類似。[2]

1. http://en.wikipedia.org/wiki/Memory_management_unit

2. http://developer.apple.com/library/mac/#documentation/Performance/Conceptual/ManagingMemory/Articles/AboutMemory.html


iPhone沒有動態內存交換,如果你在堆中分配了一些動態內存如NSString,即使系統內存不夠了,系統也不會將它寫到磁碟中來整理出一些內存,取而代之的是一個內存警告。動態內存交換對手持系統來說要求太高,因此沒有啟用。


說個對開發 App 影響最大的:從OS層面來說 iOS 發現內存不足時會向 App 發送內存不足的消息,App 有義務釋放儘可能多的內存,如果 App 不釋放的話 OS 會幹掉 App。Windows 也有內存警告消息,不過不會強制結束 App。

所以開發 iOS 時必須做好隨時被幹掉的準備,不能因此出現錯誤或者讓用戶奇怪的行為。


Both OS X and iOS include a fully-integrated virtual memory system that you cannot turn off; it is always on. Both systems also provide up to 4 gigabytes of addressable space per 32-bit process. In addition, OS X provides approximately 18 exabytes of addressable space for 64-bit processes. Even for computers that have 4 or more gigabytes of RAM available, the system rarely dedicates this much RAM to a single process.

To give processes access to their entire 4 gigabyte or 18 exabyte address space, OS X uses the hard disk to hold data that is not currently in use. As memory gets full, sections of memory that are not being used are written to disk to make room for data that is needed now. The portion of the disk that stores the unused data is known as the backing store because it provides the backup storage for main memory.

Although OS X supports a backing store, iOS does not. In iPhone applications, read-only data that is already on the disk (such as code pages) is simply removed from memory and reloaded from disk as needed. Writable data is never removed from memory by the operating system. Instead, if the amount of free memory drops below a certain threshold, the system asks the running applications to free up memory voluntarily to make room for new data. Applications that fail to free up enough memory are terminated.


ios的內存管理,每個對象都有一個retain count。只有retian count為0時候對象的內存唄回收。


ios沒有虛擬內存


ios的內存管理採用的是手動回收機制,每次alloc init / new / copy執行過後,針對某對象的內存計數器將會+1,該對象執行一次release操作則-1。當計數器為0時,則該對象被回收。若計數器當前計數為0,依然執行release的話,程序則會crash。


推薦閱讀:

TAG:iOS | MicrosoftWindows | iOS開發 |