gpt4 book ai didi

objective-c - 将 UIAlertView 委托(delegate)给另一个类/文件?不工作?

转载 作者:行者123 更新时间:2023-11-29 04:27:32 24 4
gpt4 key购买 nike

所以我是 iOS 开发新手,我正在尝试将按钮单击事件委托(delegate)给另一个类。每当我单击警报上的按钮时,应用程序就会崩溃,并且收到一条错误消息“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

这是我的 View 文件的实现..

#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

最佳答案

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

并且您可能会泄漏委托(delegate)类。您应该在 View Controller 中声明一个强/保留属性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];
}

关于objective-c - 将 UIAlertView 委托(delegate)给另一个类/文件?不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12126450/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com