2

これは、状況の詳細が多すぎる可能性がある以前の質問からのフォローアップの質問です。次のコードを検討してください。

BarViewController.h

#import <UIKit/UIKit.h>
@protocol SomeDelegate
- (void)someCallback; // doesn't matter
@end

@interface BarViewController : UIViewController

@property (weak, nonatomic) id <SomeDelegate> delegate;

@end

BarViewController.m

#import "BarViewController.h"

@interface BarViewController ()

@end

@implementation BarViewController

@end

FooViewController.h

#import <UIKit/UIKit.h>

@interface FooViewController : UIViewController

@end

FooViewController.m

#import "FooViewController.h"
#import "BarViewController.h"

@interface FooViewController () <SomeDelegate>
@end

@implementation FooViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    BarViewController *bar = [[BarViewController alloc] init];
    // does this assignment create a "strong" reference i.e. increase retain count by 1?
    bar.delegate = self;
    // *do some useful stuff with bar.delegate here* //
    bar = nil; // is memory for bar.delegate free'd here,
    // or only after this instance of FooViewController is destroyed?
}

#pragma mark - SomeDelegate
- (void)someCallback {
// doesn't matter
}

@end

FooViewControllerそれがいくつかの小さなアプリケーションのメイン ビュー コントローラーでありBarViewController、ユーザーがいくつかのボタンの 1 つを選択できるように設計された、短命のものである と想像してください。BarViewControllerデリゲートを介して選択されたものを報告します。

上記のコードで、 inに設定barすると、 のために取っておいたメモリはどうなりますか? 一方で、に設定すると、割り当てが解除されるオブジェクトの一部としても設定される可能性があると考えています。一方、参照についての私の理解では、記憶は、それを強く指し示している人がいなくなって初めて解放されるというものです。したがって、への強い参照を作成する場合(そうしますか?)、 が であるにもかかわらず、のインスタンスへのポインターを保持している可能性はありますか? ここでメモリリークの可能性はありますか? nilFooViewController.mbar.delegatebarnilbar.delegatenilbarweakbar.delegate = selfdelegatebar.delegateFooViewControllerbarnil

編集:
したがって、私がこれについて考えている方法は、ルート ビュー コントローラーとしてのUIWindowインスタンスを強く指しFooViewController、BarViewController のインスタンスがFooViewControllerそのデリゲートとしてのインスタンスを弱く指すことです。したがって、 を設定しても、 から来る少なくとも 1 つの強いポインターをまだ持っているオブジェクトを弱く指しているbar = nilため、「他の誰も強く指していないときに弱いプロパティが解放される」という前提に基づいて解放することはできませんか?bar.delegateUIWindowbar.delegate

4

2 に答える 2