Weak、Strong、assign 和 autorelease + 1道面試題


一、weak、strong、assign的理解

1. OC 對象用 strong,爲什麼連線的ui控件卻用weak?

controller → view → view.subViews → imageView → 強引用
controller → imageView → 弱引用
controller → imageView 這個位置換成 strong 也可以,但是不建議,如果一個對象被多個對象強引用,當這多個對象中有一個對象忘記釋放,那麼該對象也不能釋放。
ARC環境指定編譯文件不使用arc -fno-objc-arc 。
補充:
讓程序兼容ARC和非ARC部分:
轉變爲非ARC   -fno-objc-arc  
轉變爲ARC   -f-objc-arc 




2.Weak 和 assign的區別

weak 對象釋放後指向0地址;
assign 對象釋放後指向地址不變,成爲野指針;


二、自動釋放池

1.MRC內存管理原則:
// 誰申請,誰釋放。
// 遇到 alloc / copy / retain,都需要添加 release 或 autorelease。

2. autorelease:
// 添加一個自動釋放的標記,會延遲自動釋放。
// 當一個autorelease的對象超出了作用域之後,會被添加到最近的自動釋放池中。
// 當自動釋放池被釋放之前,會像池中所有的對象發送release消息,釋放池中所有的對象。 

3. iOS開發中的內存管理
(1)在iOS開發中,並沒有JAVA或C#中的垃圾回收機制
(2)使用ARC開發,只是在編譯時,編譯器會根據代碼結構自動添加了retainreleaseautorelease

4. 自動釋放池的工作原理
(1)標記爲autorelease的對象在出了作用域範圍後,會被添加到最近一次創建的自動放池
(2)當自動釋放池被銷燬耗盡時,會向自動釋放池中的所有對象發送release消息

5. 自動釋放池和主線程 

原文:
The Application Kit creates an
autoreleasepool on themain threadat the beginning of every cycle of the event loop, and drains it at theend, thereby releasing any autoreleased objects generatedwhile processing an event. If you use the Application Kit, youtherefore typically don’t have to create your own pools. If your applicationcreates a lot of temporary autoreleasedobjects within the event loop, however, it may be beneficial to create “local” autoreleasepools to help to minimize the peak memory footprint. 
在主線程消息循環開始的時候創建了自動釋放池,在消息循環結束的時候清掉自動釋放池

6.什麼時候使用自動釋放池 
If youwrite a loop that creates many temporary objects.
You may use an
autoreleasepool block inside the loop to dispose of those objects before the nextiteration. Using an autoreleasepool block in the loop helps to reduce the maximum memory footprint of the application. 
循環中創建了許多臨時對象,在循環裏面使用自動釋放池,用來減少高內存佔用。


If youspawn a secondary thread.
You must create your own
autoreleasepool block as soon as the thread begins executing; otherwise, your applicationwill leak objects. (See AutoreleasePool Blocks and Threads for details.)

 開啓子線程的時候要自己創建自動釋放池,否則可能會發生內存泄露。


7.自動釋放池常見面試代碼

面試題:

int largeNumber = 999*9999;

for  ( int i = 0; i < largeNumber; ++i ) {

    NSString *str = @"Hello World";

    str = [str stringByAppendingFormat:@" - %d", i ];

    str = [str uppercaseString];

    NSLog(@"%@", str);

}

問:以上代碼存在什麼樣的問題?如果循環的次數非常大時,應該如何修改?

答:

    int largeNumber = 999*9999;

    for (int i = 0; i < largeNumber; ++i) {

        @autoreleasepool {

            NSString *str = @"Hello World";

            str = [str stringByAppendingFormat:@" - %d", i];

            str = [str uppercaseString];

            NSLog(@"%@", str);

        }   

    }











發佈了53 篇原創文章 · 獲贊 5 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章