【问题标题】:ViewController has too many line of code (options for refactoring)ViewController 的代码行太多(重构选项)
【发布时间】:2015-04-24 12:55:51
【问题描述】:

我的 ViewController 看起来非常庞大,现在有 500 多行代码。 我想对其进行重构,并将一些方法放入外部类或类别中。

但是我的很多方法都处理 IBOutlets 或 UIViewAnimation、动画 Storyboard 的 View 元素、隐藏它们、改变不透明度等。

将这些方法移出我的 ViewController 的最佳方法是什么?

- (void)animateBeforeNewRound;
- (void)animateBeforeNewGame;
- (void)animateBeforeFinishingTheGame;
- (void)presentSlidingView;

- (void)presentSlidingView {
    //preparing view constraint for animation
    __block float constr = 0;
    [self.view.constraints enumerateObjectsUsingBlock:^(NSLayoutConstraint *constraint, NSUInteger idx, BOOL *stop) {

        if (constraint.firstItem == self.slideView && constraint.firstAttribute == NSLayoutAttributeLeading) {
            constr = constraint.constant;
            [constraint setConstant:0.0f];
        }
    }];

    [UIView animateWithDuration:0.1 animations:^{
        /* animate prepared constraint */
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        /* animate constraints */
        [UIView animateWithDuration:0.1 delay:0.2 options:UIViewAnimationOptionTransitionNone animations:^{
            self.imgBubble.alpha = 1;
        } completion:^(BOOL finished) {
            /* update constraints back to initial value */
            [self.view.constraints enumerateObjectsUsingBlock:^(NSLayoutConstraint *constraint, NSUInteger idx, BOOL *stop) {
                if (constraint.firstItem == self.slide && constraint.firstAttribute == NSLayoutAttributeLeading) {
                    [constraint setConstant:constr];
                }
            }];
            [UIView animateWithDuration:0.1 delay:0.8 options:UIViewAnimationOptionTransitionNone animations:^{
                [self.view layoutIfNeeded];
            } completion:^(BOOL finished) {
                self.imgBubble.alpha = 0;
            }];
        }];
    }];
}

- (void)animate* 方法看起来与- (void)presentSlidingView 非常相似,并使用其他 Storyboard 的 IBOutlets 进行操作。

【问题讨论】:

  • 尝试为您的 viewController 创建一个自定义超类
  • @NJGadhiya 如果您的 VC 具有实现附加方法的 VC 的主要逻辑子类,这不是很奇怪吗?

标签: ios objective-c model-view-controller refactoring


【解决方案1】:

通常,使用单独的对象来处理单独的任务是个好主意。例如,您可以创建一个 Animator 类来处理您的所有 -(void)animateXX 方法。

您可以对代表进行同样的处理。我通常使用自定义实例来处理所有 UITableViewDataSource 方法,因为它使我的 Table View Controller 类不那么混乱。

关注点分离对于未来的可维护性也很有好处(例如:当您遇到与动画相关的问题时,您会知道首先要看的是您的 Animator)。

Here 是一篇很棒的文章。

【讨论】:

【解决方案2】:

作为特定功能的建议:

  1. 为约束创建出口,不要在代码中明确搜索它们,这样写会更容易(对我来说):

    self.slideViewLeadingConstraint.Constant = 0.0f;

  2. 为动画创建辅助函数;

尝试使用ReactiveCocoa 和/或ReactiveAnimation,我认为这确实有助于分离所有这些链接调用并且代码看起来更整洁;

【讨论】:

  • 虽然 ReactiveCocoa 引入了新的概念,这肯定会带来更干净、更合理的代码库,但它本身并不能解决混乱。我认为这里的关键点是适当分离关注点的重要性。忽略它,你最终会得到 1000 多行无法维护的 View Controller 代码(而且大部分都不属于那里)。
猜你喜欢
  • 2016-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-03
  • 2011-04-22
相关资源
最近更新 更多