天天看點

OC學習 第七節 手動記憶體管理

 回顧

malloc free

JAVA C# GC Garbage collection 垃圾回收機制

mac os

ARC Automatic Reference Count 自動引用計數

MRC Manual Reference Count 手動管理記憶體

引用計數

引用:強引用/弱引用

弱引用:assign

引用計數

# 手動記憶體管理(Manual Reference Counting)(應用非常靈活)MRC

ARC (Automatic Reference Counting)

堆空間 :

         1.忘記釋放  —> 記憶體洩露

         2.提前/過早釋放 ---> 記憶體崩潰

         3.多釋放  —> 崩潰 C野指針

malloc free free

         記憶體管理 管理的是堆空間

         誰來釋放?程式員負責釋放

# 記憶體管理原理

# c模拟

# retain release dealloc

# new

# setter方法中的記憶體注意事項

# 不要管太多,管好自己 黃金法則

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {

    NSMutableString *str1 = nil;

    NSMutableString *str2 = nil;

    @autoreleasepool {

        str1 = [[NSMutableString alloc] initWithString:@"Welcome to beijing"];

        str2 = [NSMutableString stringWithString:@"Welcome to zhenzhou"];

        NSLog(@"%@ %ld", str1, str1.retainCount);

        NSLog(@"%@ %ld", str2, str2.retainCount);

    }

    NSLog(@"-------------------------");

    [str1 setString:@"Respect China"];

    [str1 release];

    [str1 release];

    NSLog(@"%@ %ld", str1, str1.retainCount);

    //[str2 release];

    //NSLog(@"%@ %ld", str2, str2.retainCount);

    return 0;

}

# 字元串的copy/mutableCopy

注:

Dog *dog2 = [dog1 copy];

在使用copy /mutableCopy的時候 ,使用的對象所屬的類必須要遵守協定NSCopying /NSMutableCopying協定,實作裡面的方法。

因為在執行copy函數的時候,内部會調用目前對象的copyWithZone:方法, 是以使用copy前 必須要遵守協定實作copyWithZone:方法

NSString NSArray NSDictionary 這些類都遵守了拷貝協定 實作了裡面的方法,可以直接用copy 。可以字元串對象常常用拷貝函數

# dealloc

# 記憶體管理之屬性要注意的地方

# autorelease和自動釋放池

# 數組/字典的記憶體管理