OC ARC之基本使用(代码分析)

  1 //
  2 //  main.m
  3 //  01-arc的基本使用
  4 //
  5 //  Created by apple on 13-8-11.
  6 //  Copyright (c) 2013年 itcast. All rights reserved.
  7 //
  8 
  9 
 10 #import <Foundation/Foundation.h>
 11 
 12 @class Dog;
 13 
 14 @interface Person : NSObject
 15 
 16 @property (nonatomic, strong) Dog *dog;
 17 
 18 
 19 @property (nonatomic, strong) NSString *name;
 20 
 21 @property (nonatomic, assign) int age;
 22 
 23 @end
 24 
 25 #import "Person.h"
 26 
 27 @implementation Person
 28 
 29 - (void)dealloc
 30 {
 31     NSLog(@"Person is dealloc");
 32     
 33     // [super dealloc];
 34 }
 35 
 36 @end
 37 
 38 
 39 #import <Foundation/Foundation.h>
 40 
 41 @interface Dog : NSObject
 42 
 43 @end
 44 
 45 #import "Dog.h"
 46 
 47 @implementation Dog
 48 - (void)dealloc
 49 {
 50     NSLog(@"Dog is dealloc");
 51 }
 52 @end
 53 
 54 
 55 
 56 #import <Foundation/Foundation.h>
 57 #import "Person.h"
 58 #import "Dog.h"
 59 /*
 60  ARC的判断准则:只要没有强指针指向对象,就会释放对象
 61  
 62  
 63  1.ARC特点
 64  1> 不允许调用release、retain、retainCount
 65  2> 允许重写dealloc,但是不允许调用[super dealloc]
 66  3> @property的参数
 67   * strong :成员变量是强指针(适用于OC对象类型)
 68   * weak :成员变量是弱指针(适用于OC对象类型)
 69   * assign : 适用于非OC对象类型
 70  4> 以前的retain改为用strong
 71  
 72  指针分2种:
 73  1> 强指针:默认情况下,所有的指针都是强指针 __strong
 74  2> 弱指针:__weak
 75  
 76  */
 77 
 78 int main()
 79 {
 80     Dog *d = [[Dog alloc] init];
 81     
 82     Person *p = [[Person alloc] init];
 83     p.dog = d;
 84     
 85     d = nil;
 86     
 87     NSLog(@"%@", p.dog);
 88     
 89     return 0;
 90 }
 91 
 92 void test()
 93 {
 94     // 错误写法(没有意义的写法)
 95     __weak Person *p = [[Person alloc] init];
 96     
 97     
 98     NSLog(@"%@", p);
 99     
100     NSLog(@"------------");
101 }
原文地址:https://www.cnblogs.com/oc-bowen/p/5053785.html