ios遗传与目标c,如何调用一个方法,而不是重复它
我用objective-C启动了一个新的iOS应用程序。我有一种方法,它显示一个警报框,我意识到我在所有的ViewController中都使用它。实现这个方法的最好方法是什么,这样我就不必重复了?我是否应该创建另一个视图控制器并将其导入所有其他视图控制器?有不同类型的课程吗ios遗传与目标c,如何调用一个方法,而不是重复它,ios,objective-c,class,Ios,Objective C,Class,我用objective-C启动了一个新的iOS应用程序。我有一种方法,它显示一个警报框,我意识到我在所有的ViewController中都使用它。实现这个方法的最好方法是什么,这样我就不必重复了?我是否应该创建另一个视图控制器并将其导入所有其他视图控制器?有不同类型的课程吗 - (void) alertStatus:(NSString *)msg :(NSString *)title { UIAlertView *alertView = [[UIAlertView alloc] ini
- (void) alertStatus:(NSString *)msg :(NSString *)title
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
message:msg
delegate:self
cancelButtonTitle:@"Ok"
otherButtonTitles:nil, nil];
[alertView show];
}
您有多种解决方案:
showartstatus(NSString*msg,NSString*title){…}
+(void).
创建一个助手类,并将其称为合适的名称,例如:[MyHelper alertStatus:…]
有两种方法可以解决这个问题 选择一 创建负责显示警报的独特类 比如说
ABCAlertViewPresenter
。然后在这个类中,您可以添加代码来执行演示。类似于-[ABCAlertViewPresenter presentAlertWithStatus:title:][/code>
这种方法的好处是,您可以从视图控制器中提取警报演示文稿,这也会使转换到UIAlertController
更容易,因为UIAlertView
是:
if ([UIAlertController class]) {
//show an alert controller
UIAlertController *alert = [UIAlertController alertControllerWithTitle:alertTitle
message:alertMessage
preferredStyle:UIAlertControllerStyleAlert];
[viewController presentViewController:alert animated:YES completion:nil];
} else {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:alertTitle
message:alertMessage
delegate:nil
cancelButtonTitle:nil
otherButtonTitles:nil];
[alertView show];
}
选择二
将所有演示文稿和导航代码移动到导航协调器类中。这将删除我们倾向于在视图控制器与其显示的视图控制器对应项之间创建的依赖关系。如果您曾经在UIViewController
中调用过self.navigationController pushViewController…
,那么您已经在控制器之间添加了依赖项。这使得自定义动画演示甚至添加新的视图控制器变得相当困难
然后,您可以创建一个默认的基本UIViewController并公开协调控制器(它可以是单例或应用程序委托上的属性,甚至可以是您自己的UINavigationController子类上的属性)。然后,当您想要显示警报或控制器时,请询问协调员:
[self.coordinationController presenAlertViewFromViewController:self
title:AlertTitle
message:alertMessage];
使用此方法为UIAlertView添加类别尝试此。。。我们可以使用NSNotification
在您的一个ViewController
类中。。
例如:FirstViewController.m
添加以下代码
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(alertStatus:) name:@"ShowAlert" object:nil];
}
-(void)alertStatus:(NSNotification*)sender
{
UIAlertView * alert = [[UIAlertView alloc]initWithTitle:[sender.userInfo objectForKey:@"title"]
message:[sender.userInfo objectForKey:@"message"]
delegate:self
cancelButtonTitle:@"ok"
otherButtonTitles:nil];
[alert show];
}
在其他类中,您希望显示警报。。。
例如:AnotherViewController.m
像这样调用通知
[[NSNotificationCenter defaultCenter] postNotificationName:@"ShowAlert" object:nil userInfo:@{@"title":@"Alert1",@"message":@"This is first alert"}];
这根本不能解决她的问题,因为现在每个视图控制器都需要发布此通知并响应该通知?“没关系,老师,我真的不明白你在说什么……:)@Daniel GalaskoRead问这个问题,先生,她在试图避免重复代码。您的解决方案是在视图控制器中发布通知并侦听这些通知。因此,您正在复制警报代码:)