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

iOS 基本記憶體管理:@class、循環 retain 與解決方式

編輯:iOS 開發綜合

在 Objective-C 中,@class 常用於標頭檔的前向宣告,特別是在兩個類別彼此引用時,可以有效避免重複匯入與編譯依賴問題。但非 ARC 環境下,若雙方互相 retain,仍可能造成循環引用。

@class 的作用

當 Person 類別引用 Card,而 Card 又引用 Person 時,若在標頭檔中直接互相 #import,容易造成循環包含。使用 @class 可以先告訴編譯器這是一個類別名稱,等到實作檔真正需要存取時再匯入。

@class Card;

@interface Person : NSObject

@property (nonatomic, retain) Card *card;

@end

循環 retain 問題

若 Person retain Card,而 Card 也 retain Person,兩者的參考計數都不會歸零,導致物件無法釋放。

解決方式

常見做法是兩端互相引用時,一端使用 retain,另一端使用 assign 或 weak。以下以 Person 與 Card 為例。

#import <Foundation/Foundation.h>

@class Card;

@interface Person : NSObject

@property (nonatomic, retain) Card *card;

@end
#import "Person.h"
#import "Card.h"

@implementation Person

- (void)dealloc {
    [_card release];
    NSLog(@"Person 被回收");
    [super dealloc];
}

@end
#import <Foundation/Foundation.h>

@class Person;

@interface Card : NSObject

@property (nonatomic, assign) Person *person;

@end
#import "Card.h"
#import "Person.h"

@implementation Card

- (void)dealloc {
    NSLog(@"Card 被回收");
    [super dealloc];
}

@end

使用範例

Person *person = [[Person alloc] init];
Card *card = [[Card alloc] init];

person.card = card;
card.person = person;

[card release];
[person release];

在這個結構中,Person 擁有 Card,因此使用 retain;Card 只是反向指向 Person,因此使用 assign。這樣可避免循環 retain,讓物件能正常釋放。

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