在两个 class 之间使用 UIAlertView 委托

Using UIAlertView delegate between two class

我有2个classes,在classB.I中有一个UIAlertView叫classB在classA中的alertView,但是B的alert视图从不进入其委托方法。

class一个

B* b = [[b alloc]init];
[b check];

class B

-(void)check
{
       [[UIAlertView alloc]initWithTitle:@“Tips” message:@“hello”  delegate:self cancelButtonTitle:@“Cancel” otherButtonTitles:@“Yes”, nil];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:    (NSInteger)buttonIndex
{
    if (buttonIndex == 1)
    {
        NSLog();
    }
}

` 我认为这是委托的问题,但我尝试了很多方法都是徒劳的,我怎样才能让它发挥作用。

您的 class B 应该符合 UIAlertViewDelegate 协议。我同意@tanzolone 关于保留您的对象 B 的观点。 这是代码示例
Class一个

#import "ClassA.h"
#import "ClassB.h"

@interface ClassA()

@property (nonatomic) ClassB *classB;

@end

@implementation ClassA

- (void)yourMethodName {
    self.classB = [ClassB new];
    [self.classB check];
}

@end

ClassB

#import "ClassB.h"

@interface ClassB()<UIAlertViewDelegate>

@end

@implementation ClassB

- (void)check {
    [[[UIAlertView alloc] initWithTitle:@"Tips" message:@"message" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Ok", nil] show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        NSLog(@"works");
    }
}

@end

我敢打赌问题是您在调用检查后没有保留对象 b。 UIAlertView 委托是一个弱 属性 - 因此,如果 b 在您呈现调用 check 的警报视图后被释放,则当用户与警报视图。保留对 b 的强引用(例如在 class a 中使用强引用 属性 并重试。

我只想补充一点,UIAlertView 实际上在 iOS9 中已弃用 - 如果您不需要支持 iOS7,您应该使用 UIAlertController(preferredStyle 为 UIAlertControllerStyleAlert)而不是 UIAlertView。 UIAlertController 已在 iOS8 中可用,因此只有在您的应用仍支持 iOS7.

时才真正需要使用 UIAlertView