zoukankan      html  css  js  c++  java
  • iOS ARC下循环引用的问题 -举例说明strong和weak的区别

    strong:适用于OC对象,作用和非ARC中的retain作用相同,它修饰的成员变量为强指针类型
    weak:适用于OC对象,作用和非ARC中的assign作用相同,修饰的成员变量为弱指针类型
    assign:适用于非OC对象类型

    在OC对象循环引用的时候一端为strong类型,另一段为weak类型

    示例代码如下:
    /****************************** Teacher.h文件 ***********************************/
    #import <Foundation/Foundation.h>
    @class Student;
    @interface Teacher : NSObject
    @property (nonatomic,strong) Student *student;
    @property (nonatomic,strong) NSString *teacherName;
    @end
    
    /****************************** Teacher.m文件 ***********************************/
    #import "Teacher.h"
    #import "Student.h"
    @implementation Teacher
    - (void)dealloc
    {
        NSLog(@"叫%@的Teacher对象被销毁了",_teacherName);
    }
    @end
    
    /****************************** Student.h文件 ***********************************/
    #import <Foundation/Foundation.h>
    @class Teacher;
    @interface Student : NSObject
    @property (nonatomic,weak) Teacher *teahcher;
    @property (nonatomic,strong) NSStirng *studentName;
    @end
    
    
    /****************************** Student.m文件 ***********************************/
    #import "Student.h"
    #import "Teacher.h"
    @implementation Student
    - (void)dealloc
    {
        NSLog(@"叫%@的Student对象被销毁了",_stuName);
    }
    @end
    
    /****************************** main.m文件 ***********************************/
    #import <Foundation/Foundation.h>
    #import "Teacher.h"
    #import "Student.h"
    int main(int argc, const char * argv[])
    {    
        Teacher *teacher = [[Teacher alloc] init];
        teacher.teacherName  = @"张老师";
        
        Student *student = [[Student alloc] init];
        student.stuName = @"李同学";
        
      // Student类对象中的Teacher属性为弱引用
        student.teahcher = teacher;
        
        // Teacher类对象中的Student属性为强引用
        teacher.student = student;
    
        return 0;
    }

    main方法中代码的简单内存图如下:

  • 相关阅读:
    tensorflow 2.0 学习 (十) 拟合与过拟合问题
    tensorflow 2.0 学习 (九) tensorboard可视化功能认识
    tensorflow 2.0 学习 (八) keras模块的认识
    tensorflow 2.0 学习 (七) 反向传播代码逐步实现
    tensorflow 2.0 学习 (六) Himmelblua函数求极值
    tensorflow 2.0 学习 (五)MPG全连接网络训练与测试
    arp协议简单介绍
    Pthread spinlock自旋锁
    线程和进程状态
    内核态(内核空间)和用户态(用户空间)的区别和联系·
  • 原文地址:https://www.cnblogs.com/QM80/p/3599695.html
Copyright © 2011-2022 走看看