私は今日これについて考えていましたが、今テストしたところ、少し混乱しています…</p>
viewController をナビゲーション スタックにプッシュするか、ViewController をモーダルに提示することによって viewController を使用する場合、メモリ管理について疑問に思っています。
モーダルの例を思考実験として使用してみましょう。ビューを作成して表示するためのソースは次のとおりです。私の例では、ARC かどうかは関係ないので、両方を示します。
ARC の場合:
ViewController *myViewController = [[ViewController alloc] init];
myViewController.delegate = self;
[self presentViewController:myViewController animated:YES completion:NULL];
ARC なし:
ViewController *myViewController = [[ViewController alloc] init];
myViewController.delegate = self;
[self presentViewController:myViewController animated:YES completion:NULL];
[myViewController release]; //As it's now 'owned' by the presenting View controller
これは、既存のViewControllerの上にviewControllerをモーダルに表示する方法についての私の理解です。
この例では、上記のコードが、ViewController を表示するためにボタンがタッチされたときに呼び出されるメソッドにあるとします。
さて、私の質問に、
私がやっていることは、ボタンがタッチされるたびにこのコードを呼び出すことです。Instruments でのテスト中、リークはないようでした。-ただし、myViewController のdeallocおよびviewDidLoadメソッドにNSLog ステートメントがあるため、ボタンに触れるたびにインスタンス化されますが、割り当てが解除されることはありません。
そう...
A)新しい viewController を作成し、表示するたびに古いものをリークしているように見えるため、(ARC を使用しているかどうかに関係なく) インストゥルメントでリーク表示 (または Live Bytes の上昇) が表示されないのはなぜですか。
B)これがメモリセーフでない場合、上記のコードを書く正しい方法は何ですか? この種のコード スニペットは、Apple のサンプル コードやインターネットのいたるところで見られます。私 (そして彼ら) は、オブジェクトが既に作成されているかどうかを確認するために、ifステートメントで alloc init 行をラップするべきではありませんか?
すなわち
if(!myViewController)
{
ViewController *myViewController = [[ViewController alloc] init];
}
myViewController.delegate = self;
[self presentViewController:myViewController animated:YES completion:NULL];
読んで答えてくれてありがとう、私はずっと上記のコードを使って ViewControllers を作成、プッシュ、提示してきましたが、リークに気付かなかったので、これについて本当に疑問に思っています! - 戻ってすべてを書き直さなければならないかもしれません!
混乱を避けるために注意してください:デリゲート プロパティは、UIViewController サブクラス (デリゲート プロトコルを実装した場所) のカスタム プロパティであり、モーダルに存在する Viewcontroller を適切に閉じるために必要です。コーディングガイドラインに従って。
よろしく、ジョン
リクエストに応じて編集、デリゲートの作成:
.h
@protocol NotificationManagementViewControllerDelegate;
@interface NotificationManagementController :
{
__weak NSObject <NotificationManagementViewControllerDelegate> *delegate;
}
@property (nonatomic, weak) NSObject <NotificationManagementViewControllerDelegate> *delegate;
@protocol NotificationManagementViewControllerDelegate <NSObject>
@optional
- (void)didFinishSettingNotification:(NotificationManagementController *)notificationManagementController;
.m
- (void)sendMessageToDismiss {
if ([[self delegate] respondsToSelector:@selector(didFinishSettingNotification:)]) {
[self.delegate didFinishSettingNotification:self];
}
}
そして最後にデリゲート .m:
- (void)didFinishSettingNotification:(NotificationManagementController *)notificationManagementController
{
[self dismissViewControllerAnimated:YES completion:NULL];
}