UIAlertView にコンテキストを提供する方法についていくつかのアイデアを見てきました。一般的な答えは、辞書またはサブクラスの UIAlertView に保存することです。コンテキストを辞書に保存するという考えは好きではありません。データの場所が間違っています。UIAlertView のサブクラス化は Apple ではサポートされていないため、私の基準では、良い解決策ではありません。
アイデアは思いつきましたが、どうすればよいかわかりません。UIAlertView のデリゲートであるコンテキスト オブジェクトのインスタンスを作成します。アラート ビュー コンテキストには、View Controller である独自のデリゲートがあります。
問題はメモリの解放です。alertView.delegate を nil に設定し、[self autorelease] を呼び出して -alertView:didDismissWithButtonIndex: のコンテキスト オブジェクトを解放します。
質問は: 私は自分自身にどのような問題を引き起こしていますか? 微妙なメモリ エラーに備えている疑いがあります。
-alertView:clickedButtonAtIndex のみをサポートする単純なバージョンを次に示します。
使用する
- (void)askUserIfTheyWantToSeeRemoteNotification:(NSDictionary *)userInfo
{
[[[[UIAlertView alloc] initWithTitle:[userInfo valueForKey:@"action"]
message:[userInfo valueForKeyPath:@"aps.alert"]
delegate:[[WantAlertViewContext alloc] initWithDelegate:self context:userInfo]
cancelButtonTitle:@"Dismiss"
otherButtonTitles:@"View", nil] autorelease] show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex withContext:(id)context
{
if (buttonIndex != alertView.cancelButtonIndex)
[self presentViewForRemoteNotification:context];
}
インターフェース
@protocol WantAlertViewContextDelegate <NSObject>
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex withContext:(id)context;
@end
@interface WantAlertViewContext : NSObject <UIAlertViewDelegate>
- (id)initWithDelegate:(id<WantAlertViewContextDelegate>)delegate context:(id)context;
@property (assign, nonatomic) id<WantAlertViewContextDelegate> delegate;
@property (retain, nonatomic) id context;
@end
実装
@implementation WantAlertViewContext
- (id)initWithDelegate:(id<WantAlertViewContextDelegate>)delegate context:(id)context
{
self = [super init];
if (self) {
_delegate = delegate;
_context = [context retain];
}
return self;
}
- (void)dealloc
{
[_context release];
[super dealloc];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
[self.delegate alertView:alertView clickedButtonAtIndex:buttonIndex withContext:self.context];
}
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
alertView.delegate = nil;
[self autorelease];
}
@synthesize delegate = _delegate;
@synthesize context = _context;
@end