您的位置:首页 > 移动开发 > Objective-C

Objective-C内存管理第六弹:ARC

2015-12-13 21:57 369 查看
//main.m

#import <Foundation/Foundation.h>
#import "Person.h"
#import "Dog.h"
/*
ARC Automatic Reference Counting 自动引用计数

ARC 编译器特性
编译器会在适当的适合,加入内存管理代码

强指针:默认所有的指针都是强指针
只要是有强指针指向一个对象,那么这个对象就不会被释放
只要没有强指针指向一个对象,那么这个对象就会被立即回收
__strong 强指针标示符,但是默认所有指针都是强指针,所以基本没有用。

弱指针:弱指针指向的对象不影响对象回收

注意:不要用弱指针指向一个刚刚创建的对象
当出现循环引用的时候,必须要有一端是弱指针
*/

int main1(int argc, const char * argv[]) {
@autoreleasepool {

{
__strong Person * p0 = [[Person alloc] init];
}

//        Person * operson = [[Person alloc] init];
//
//        operson = nil;

}
return 0;
}

//int main2(int agrc, const char * argv[]) {
//
//    @autoreleasepool {
//
//        Person * person = [[Person alloc] init];
//        Dog * dog = [[Dog alloc] init];
//
//        person.dog = dog;
//
//    }
//}

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

@autoreleasepool {

Person * person = [[Person alloc] init];
{

Dog * dog = [[Dog alloc] init];
person.dog = dog;
}
}
}

//当弱指针指向这个对象的时候,那么创建出来就被回收了。
void test3(int argc, const char *argv[]) {
@autoreleasepool {

__weak Person * person = [[Person alloc] init];

NSLog(@"%p", person);
person.dog = nil;

}
}

int main(int agrc, const char * argv[]) {
@autoreleasepool {
Person * person = [[Person alloc] init];
Dog * dog = [[Dog alloc] init];

//把狗给人
person.dog = dog;

//把人给狗
dog.person = person;
}
return 0;
}


//Person.h

#import <Foundation/Foundation.h>
#import "Dog.h"

@interface Person : NSObject
{
Dog * _dog;
}

- (void)setDog:(Dog *)dog;

@end


//Person.m

#import "Person.h"

@implementation Person

//ARC中不用再写dealloc方法中的[super dealloc]了,只需要验证对象是否被销毁了。

- (void)setDog:(Dog *)dog {

_dog = dog;
}

- (void)dealloc
{

NSLog(@"%s", __func__);
}

@end


//Dog.h

#import <Foundation/Foundation.h>
@class Person;

@interface Dog : NSObject
{
__weak Person * _person;
}

- (void) setPerson:(Person *)person;

@end


//Dog.m

#import "Dog.h"

@implementation Dog

- (void)setPerson:(Person *)person {

_person = person;
}

- (void)dealloc
{
NSLog(@"%s", __func__);
}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: