在两个类之间使用UIAlertView委托

时间:2016-06-17 10:08:40

标签: ios uialertview

我有2个类,在类B.中有一个UIAlertView。我在类A中调用了类B的alertView,但是B的警报视图从不进入它的委托方法。

A级

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

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();
    }
}

`  我认为这是委托的问题,但我尝试了许多方法是徒劳的,我怎么能让它工作。

2 个答案:

答案 0 :(得分:1)

我打赌问题是你在调用check之后不保留对象b。 UIAlertView委托是一个弱属性 - 因此,如果在您提供调用b的警报视图后check被释放,则当用户与警报视图进行交互时,委托将为nil。强烈引用b(例如,在a类中使用强大的属性),然后重试。

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

答案 1 :(得分:-1)

您的B类应符合 UIAlertViewDelegate 协议。我同意@tanzolone关于保留你的对象B. 这是代码示例
的示例 A类

#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