何时可以通过将代码放在AppDelegate中来减少代码重复?

问题描述:

我有一个非常小的Xcode项目与几个视图控制器。我发现自己在其中复制了以下方法:何时可以通过将代码放在AppDelegate中来减少代码重复?

- (void)postTip:(NSString *)message { 
    [self postInfoAlertWithTitle:@"Tip" andMessage:message andAction:@"Got it!"]; 
} 

- (void)postInfoAlertWithTitle:(NSString *)title andMessage:(NSString *)message andAction:(NSString *)action { 
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert]; 
    [alert addAction:[UIAlertAction actionWithTitle:action style:UIAlertActionStyleDefault handler:nil]]; 
    [self presentViewController:alert animated:YES completion:nil]; 
} 

当然,这让我想到如何删除(或至少减少)重复的代码。

答案显然是把所期望的行为在父类,再有我的视图控制器从类继承。然而,一些视图控制器的类型UICollectionViewController的,有些是类型的UITableViewController的,我不知道如何维护自己的收集和表口味,分别是我让他们从一个假设MyViewController继承的事件是,一个UIViewController中。

所以,我做了一些研究,并采取了看看协议。最初,这看起来很合适,除了你不能为协议中声明的方法提供默认的实现,这基本上是我想要的。

最后,有太多的犹豫和自我厌恶,我认为把行为在我AppDelegate类中,有一个额外的参数,以方便呈现警报:

- (void)postTip:(NSString *)message toController:(UIViewController *)controller; 
- (void)postInfoAlertWithTitle:(NSString *)title andMessage:(NSString *)message andAction:(NSString *)action toController:(UIViewController *)controller; 

在一个给定的视图控制器看起来通话像这样:

[self.appDelegate postTip:@"Git gud!" toController:self]; 

等瞧!我想要的行为,我想要的行为,以及我必须做的所有事情都得到了AppDelegate的实例!但是......这并不适合我。它似乎...臭。此外,仍然有一些重复,即声明和初始化一个私有appDelegate属性,我已经注意到了这一点,而不是在需要它的地方调用(AppDelegate *)[[UIApplication sharedApplication]委托],以便:

  • 我可以指定“弱”和避免可能保留周期
  • 我只取指针的AppDelegate(欢呼为过早的优化>。<)

是否认为是可接受使用的AppDelegate作为存储库对于应用程序范围的行为,如实用程序方法,如果是这样,我是不是必需的ily偏执实施重新:使用财产? (如果没有,我有哪些选择?)

+4

在'UIViewController'上创建一个类别,它具有方法(最初的,而不是AppDelegate的)。 'UICollectionViewController'和'UITableViewController'继承自'UIViewController',所以应该没问题。避免像这样使用你的AppDelegate添加太多无关的信息。你现实中使用的是事实是它是一个单身(可以由你自己做出)。 – Larme

+1

您可以创建一个“TipHelper”类,并在您的各种控制器中使用该类的实例(或共享实例)。由于继承不是一个简单的选择,组合是另一种可用策略。 –

+0

拉美 - 啊,我不知道类别!非常有趣,我认为,只是票! – kuipersn

这在我看来,类别被用于正是这种情况 - 虽然是别人的评论所指出的,也有更多的选择 - 这是什么我已经做好了。

若要查看苹果的类别的文档,请this page。 要添加在Xcode类别,看到this page

通过创建h和.m文件

肯定使用一个类的UIViewController + InfoAlert.h

@interface UIViewController (InfoAlert) 

- (void)postInfoAlertWithTitle:(NSString *)title andMessage:(NSString *)message andAction:(NSString *)action; 

@end 

的UIViewController + InfoAlert.m

#import "UIViewController+InfoAlert.h" 

@implementation UIViewController (InfoAlert) 

- (void)postInfoAlertWithTitle:(NSString *)title andMessage:(NSString *)message andAction:(NSString *)action { 
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert]; 
    [alert addAction:[UIAlertAction actionWithTitle:action style:UIAlertActionStyleDefault handler:nil]]; 
    [self presentViewController:alert animated:YES completion:nil]; 
} 

@end 

则只需导入你的UIViewController + InfoAlert。h您想在哪里使用您的新postInfoAlertWithTitle方法