ARC使用和注意点

来源:互联网 发布:数据分析报告撰写要求 编辑:程序博客网 时间:2024/06/04 18:34

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];

    //弱指针

   __weakStudent *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对象也不存在强指针指向,最后都被回收。


0 0
原创粉丝点击