0

UIAlertView のような独自のデリゲートを持つ ARCfied シンプルなラッパー (customAlert と呼びましょう) があります。

@protocol customAlert
-(void)pressedOnYES;
- (void)pressedNO

カスタム アラート自体には強力なプロパティとして UIAlertView が含まれており、alertView.delegate = self; (customAlert は UIAlertView のデリゲートです)

私が抱えている問題 - UIAlertView デリゲートのメソッドが呼び出されると、customAlert の割り当てが解除されます。

フェ

customAlert *alert = [customAlert alloc] initWithDelegate:self];
[alert show]; // it will call customAlert [self.alertView show]

customAlert は実行ループで割り当て解除され、次のイベント (UIAlertView ボタンを押すと割り当て解除されたオブジェクトに送信されます)

それを避けるために、どうにかして customAlert オブジェクトを保持する必要があります (customAlert インスタンスのプロパティは使用できません)

4

1 に答える 1

0

あなたが直面している問題については、即時の修正として、「alert」をローカル オブジェクトとして保持するのではなく、クラスの強力なプロパティとして宣言してみてください。

ただし、customAlert のプロパティとして「UIAlertView」を使用するのではなく、「customAlert」を「UIAlertView」のサブクラスとして保持することをお勧めします。

カスタム アラート クラスの例 (コメントはあまり追加していません。コードは単純で自己記述的です)。

CustomAlert.h

    #import <UIKit/UIKit.h>

    @protocol customAlertDelegate<NSObject>
    - (void)pressedOnYES;
    - (void)pressedNO;
    @end

    @interface CustomAlert : UIAlertView
    - (CustomAlert *)initWithDelegate:(id)delegate;
    @property (weak) id <customAlertDelegate> delegate1;
    @end

CustomAlert.m

#import "CustomAlert.h"

@implementation CustomAlert
@synthesize delegate1;


- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

- (CustomAlert *)initWithDelegate:(id)delegate
{
    self = [super initWithTitle:@"Title" message:@"Message" delegate:self cancelButtonTitle:@"No" otherButtonTitles:@"Yes", nil];
    if (self) {
        //Assigning an object for customAlertDelegate
        self.delegate1 = delegate;
    }

    return self;
}
//Method called when a button clicked on alert view
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex) {
        [self.delegate1 pressedOnYES];
    } else {
        [self.delegate1 pressedNO];
    }
}
@end

デリゲート メソッドを使用したビュー コントローラー

ViewController.h

#import <UIKit/UIKit.h>
#import "CustomAlert.h"

@interface ViewController : UIViewController <customAlertDelegate>
@end

ViewController.m

#import "ViewController.h"

@implementation ViewController

- (IBAction)pressBtn:(id)sender
{
    CustomAlert *alert=[[CustomAlert alloc] initWithDelegate:self] ;
   [alert show];
}

- (void)pressedOnYES
{
    //write code for yes
}

- (void)pressedNO
{
    //write code for No
}

@end
于 2013-07-01T14:38:05.747 に答える