·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> app软件开发 >> IOS开发 >> iOSARC下循环引用的问题-举例说明strong和weak的区别

iOSARC下循环引用的问题-举例说明strong和weak的区别

作者:佚名      IOS开发编辑:admin      更新时间:2022-07-23
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方法中代码的简单内存图如下: