在 ARC 環境中,物件預設多為 strong 引用。若兩個物件互相持有對方,就可能形成循環引用,導致兩者都無法被釋放。解決方式通常是一端使用 strong,另一端使用 weak。
#import <Foundation/Foundation.h>
@class Student;
@interface Teacher : NSObject
@property (nonatomic, strong) Student *student;
@property (nonatomic, strong) NSString *teacherName;
@end
#import "Teacher.h"
#import "Student.h"
@implementation Teacher
- (void)dealloc {
NSLog(@"Teacher 被銷毀: %@", _teacherName);
}
@end
#import <Foundation/Foundation.h>
@class Teacher;
@interface Student : NSObject
@property (nonatomic, weak) Teacher *teacher;
@property (nonatomic, strong) NSString *studentName;
@end
#import "Student.h"
#import "Teacher.h"
@implementation Student
- (void)dealloc {
NSLog(@"Student 被銷毀: %@", _studentName);
}
@end
Teacher *teacher = [[Teacher alloc] init];
teacher.teacherName = @"張老師";
Student *student = [[Student alloc] init];
student.studentName = @"李同學";
student.teacher = teacher;
teacher.student = student;
在這個例子中,Teacher 強引用 Student,而 Student 弱引用 Teacher。當外部不再持有這兩個物件時,循環引用不會阻止它們被釋放。