0

所以我是 iOS 开发的新手,我正在尝试将按钮单击事件委托给另一个类。每当我单击警报上的按钮时,应用程序就会崩溃,并且我收到一条错误消息 Thread_1 EXC_BAD_ACCESS。

这是我的代码。

// theDelegateTester.h
#import <UIKit/UIKit.h>

@interface theDelegateTester : UIResponder <UIAlertViewDelegate>
- (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex;
@end

执行..

// theDelegateTester.m
#import "theDelegateTester.h"

@implementation theDelegateTester
- (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    NSLog(@"Delegated");
}
@end

这是我的视图文件的实现..

#import "appleTutorialViewController.h"
#import "theDelegateTester.h"

@interface appleTutorialViewController ()
- (IBAction)tapReceived:(id)sender;
@end

@implementation appleTutorialViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)viewDidUnload
{
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}



- (IBAction)tapReceived:(id)sender {
    theDelegateTester *newTester = [[theDelegateTester alloc] init];
    UIAlertView *myAlert = [[UIAlertView alloc] initWithTitle:@"Alert!" message:@"This is a delegated alert" delegate:newTester cancelButtonTitle:@"Close" otherButtonTitles:@"Cool!", nil];
    [myAlert show];
}
@end
4

1 回答 1

1

首先,您应该始终以大写字母开头类名,这样您就可以轻松地区分类和实例或方法。

而且您可能会泄漏委托类。您应该在视图控制器中声明一个强/保留属性TheDelegateTester *myDelegate。然后tapReceived:是这样的:

- (IBAction)tapReceived:(id)sender {
    if (!self.myDelegate) {
        TheDelegateTester *del = [[TheDelegateTester alloc] init];
        self.myDelegate = del;
        [del release];
    }
    UIAlertView *myAlert = [[UIAlertView alloc] initWithTitle:@"Alert!" message:@"This is a delegated alert" delegate:newTester cancelButtonTitle:@"Close" otherButtonTitles:@"Cool!", nil];
    [myAlert show];
    [myAlert release];
}
于 2012-08-25T23:35:51.757 回答