ARC使用和注意點

ARC(Automatic reference counting)管理,是爲了提高開發者的效率,節省編寫內存管理的代碼,讓開發者更關心自己的業務,並沒有真正的自動內存管理,而是編譯器在編譯前會檢查代碼,判斷對象是否被強指向,如果有指針強指向這個對象,那麼這個對象就不會被回收。

區別強指針和弱指針分別用__strong和__weak,默認所有對象的指針都是強指針,而在我們對象模型構建的時候,如果一個對象依賴於另外一個對象我們就使用強指針指向,但是如果是相互包含,那麼我們一方用強指向,另外一個方用弱指向

__strongStudent *stu=[[Studentalloc]init]; //強指針

__weakStudent *stu2=[[Studentalloc]init];//弱指針


student

#import <Foundation/Foundation.h>

@class Book;

@interface Student :NSObject

@property (nonatomic,strong)Book *book;

@end

#import "Student.h"

@implementation Student

-(void)dealloc{

    NSLog(@"對象被銷燬");

}

@end

book

#import <Foundation/Foundation.h>

@interface Book : NSObject

@end

#import "Book.h"

@implementation Book

@end


main

void test2(){

   Student *stu=[[Studentalloc]init]; //定義一個強指向的指針*stu

   Student *s=stu;    //定義一個強指向的指針s

    stu=nil; //stu被回收

    NSLog(@"stu==%@",s);

}


在內存中的運行狀態:

從以上可以得知,當stu=nil執行後中是stu的指針被清空,所以指向student對象引用也被清空,但是s的指向並沒有被清空,所以s的值還是存在。

void test1(){

   Student *stu=[[Studentalloc]init];

    //弱指針

   __weak Student *s=stu;

    stu=nil;//stu對象被銷燬

   NSLog(@"s==%@",s);

}



因爲指針s是弱指針,所以當指針stu銷燬的時候,Student的對象被回收,ARC如果發現一個對象沒有強指針指向,那麼它會把所有弱指針指向清空變爲空指針,所以s指向的是一個空對象,所以取不到S的值


從以上得知:

 1.ARC原則 只要這個對象被強指針引用着,就永遠不會銷燬

 2.默認情況下,所有的指針都是強類型的指針也叫強引用可以省略__strong


ARC模式注意:

     1.不能調用release retian autorelease retaincount

     2.可以重寫dealloc不能使用[super dealloc];

     3.@property:想長期擁有某個對象,用strong,其他對象用weak

    基本數據類型依然用assign


特殊情況一:

//這個指針永遠無法使用因爲出生就被銷燬

__weak Student *s1=[[Studentalloc]init];


特殊情況二(相互包含):

student&book

#import <Foundation/Foundation.h>

@class Book;

@interface Student :NSObject

@property (nonatomic,strong)Book *book;

@end

#import "Student.h"

@implementation Student

-(void)dealloc{

    NSLog(@"對象被銷燬");

}

@end


main

Student *stu=[[Studentalloc]init];   //強指針

Book *book=[[Bookalloc]init];//強指針

stu.book=book;

book.stu=stu;


程序運行後內存狀態


因爲兩個對象都是強指向,那麼當程序運行完以後,局部變量*stu和*book都被回收,但是student對象和book對象之間的指向是強指向,所以在內存中都沒有被釋放。

所以在我們互相依賴的時候採取以下方式,有一方採取弱指向,對student.h文件修改

#import <Foundation/Foundation.h>

@class Book;

@interface Student :NSObject

@property (nonatomic,weak)Book *book;

@end

在內存中的狀態:


當程序運行完局部變量*stu和*book被銷燬,book變量被銷燬以後,因爲book對象並沒有一個強指向的指針,在student中的book指向是弱指針,所以book對象被銷燬,當book對象被銷燬,自然對student的指向也將被銷燬,student對象也不存在強指針指向,最後都被回收。


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