UIAlertView 类别:出现错误

UIAlertView category : getting error

进展如何,我想使用 UIAlertView 类别,但出现错误 use of undeclared identifier UIAlertView & cannot find interface declaration for UIAlertView。我做错了什么?

这里is.h

#import <Foundation/Foundation.h>

@interface UIAlertView(error)

+(void)error:(NSString*)msg;

@end

这里是.m

#import "UIAlertView+error.h"

@implementation UIAlertView(error)
+(void)error:(NSString*)msg
{
    [[[UIAlertView alloc] initWithTitle:@"Error"
                            message:msg
                           delegate:nil
                  cancelButtonTitle:@"Close"
                  otherButtonTitles: nil] show];
}
@end

有什么想法吗?

这是 UIAlertView 上的一个类别,UIAlertView 在 UIKit 中,而不是 Foundation 中。所以

#import <UIKit/UIKit.h>

我建议您重新考虑使用 UIAlertController 的类别,因为 UIAlertView 已被弃用并且可以从现在起随时删除。

我精心制作了一个简单的类别包装器,它模仿 UIAlertView 的行为来帮助实现这一转变。您可以从以下要点中获取它:UIAlertController+Utilities

这是使用上述类别和条件 if 语句对您的方法进行的简单重构,以支持 8.0 之前的 iOS 版本:

+(void)error:(NSString*)msg
{
    if(([[[UIDevice currentDevice] systemVersion] compare:@"8.0" options:NSNumericSearch] != NSOrderedAscending)) {
        UIAlertController *ac = [UIAlertController alertControllerWithTitle:@"Error"
                                                                    message:msg
                                                                    actions:[UIAlertAction actionWithTitle:@"Close"
                                                                                                     style:UIAlertActionStyleCancel
                                                                                                   handler:^(UIAlertAction *action) {
                                                                                                       //add your CLOSE instructions here
                                                                                                   }], nil];

        [[[[UIApplication sharedApplication] keyWindow] rootViewController] presentViewController:ac animated:YES completion:^{
            //do whatever you want on presentation completition
        }];
    } else {
        [[[UIAlertView alloc] initWithTitle:@"Error"
                                    message:msg
                                   delegate:nil
                          cancelButtonTitle:@"Close"
                          otherButtonTitles: nil] show];
    }
}