· 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 *teacher; // 弱引用,避免循環
@property (nonatomic, strong) NSString *studentName;
@end
/****************************** Student.m *******************************/
#import "Student.h"
#import "Teacher.h"
@implementation Student
- (void)dealloc {
NSLog(@"叫 %@ 的 Student 物件被銷毀了", _studentName);
}
@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.studentName = @"李同學";
student.teacher = teacher; // Student 對 Teacher 為弱引用
teacher.student = student; // Teacher 對 Student 為強引用
return 0;
}
重點:若 Teacher 與 Student 互相以 strong 持有對方,任何一方都無法被釋放,造成記憶體洩漏。只要將其中一端(此例為 Student 對 Teacher)改為 weak,即可打破循環引用,讓 dealloc 正常被呼叫。