您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS ARC 下的循環引用:strong 與 weak 的搭配

編輯:iOS 開發綜合

在 ARC 環境中,物件預設多為 strong 引用。若兩個物件互相持有對方,就可能形成循環引用,導致兩者都無法被釋放。解決方式通常是一端使用 strong,另一端使用 weak。

strong 與 weak 的差異

  • strong:強引用,會增加物件參考計數。
  • weak:弱引用,不會增加參考計數,物件釋放後會自動設為 nil。
  • assign:通常用於非物件型別,例如基本資料型別。

範例:Teacher 與 Student

#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。當外部不再持有這兩個物件時,循環引用不會阻止它們被釋放。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved