內存管理

1.內存管理—黃金法則

The basic rule to apply is Everything that increases the reference counter with alloc,[mutable]copy[withZone:],or retain is in charge of the corresponding [auto]release.

如果對一個對象使用了alloc[mutable]copy[withZone:]retain,那麼你必須使用相應的release或者autorelease。(如果你讓這個對象的引用計數加1,那麼當你在使用完成後,需要將對象的引用計數減1)

2.對象的引用計數

(1)每個對象都有自己的引用計數,表示該對象被引用的次數,即有多少人正在同時使用該對象
(2)每個對象內部都有專門的4個字節來存儲引用計數器屬性

3.對象的深拷貝

(1)任何OC類的對象如果想進行深拷貝都需要遵守NSCoping協議,並實現協議中的方法.
(2)程序舉例
Student.h

#import <Foundation/Foundation.h>

@interface Student : NSObject <NSCopying>//遵守這個協議

@property (copy, nonatomic)NSString *name;

- (id)copyWithZone:(NSZone *)zone;

@end

Student.m

#import "Student.h"

@implementation Student

- (id)copyWithZone:(NSZone *)zone{
    Student *std = [[Student alloc] init];

    std.name = _name;//連同對象中的實例變量一起進行拷貝

    return std;
}

@end

4.autoreleasepool和autorelease

(1)autoreleasepool

自動釋放池,池子裏都是發送了autorelease消息的對象,當自動釋放池被銷燬時,會對池子中的所有對象發送一個release消息

(1)autorelease

當對象調用autorelease方法時,會把對象扔進最近的autoreleasepool中,將對象由自動釋放池管理

5.retain和copy

(1)retain修飾的只是引用計數+1
(2)copy修飾的會先創建一塊內存,再進行值拷貝

6.assign/retain和weak/strong

(1)在arc中,使用weak/strong或者assign/retain都可以
(2)而在mrc中,只能使用assign/retain
(3)assign對應weak,retain對應strong

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章