【问题标题】:Breaking Circular Dependencies between MVC objects in Cocoa iOS在 Cocoa iOS 中打破 MVC 对象之间的循环依赖关系
【发布时间】:2013-09-30 22:41:14
【问题描述】:

大家好,堆垛机,

我正在尝试使用 TDD 在 iOS 应用程序中实现 MVC,但我不断获得模型和控制器之间以及控制器和视图之间的循环依赖关系。我想紧密匹配图中所示的 Cocoa MVC 模式。 Apple 文档 (https://developer.apple.com/library/ios/documentation/general/conceptual/CocoaEncyclopedia/Model-View-Controller/Model-View-Controller.html) 的 7.2。

问题源于我对 init 的 tdd 要求:所有 MVC 对象及其所有依赖项。我需要初始化所有依赖项,以便在测试期间可以替换模拟。这是我的问题的一个简单示例。

查看:

exampleView.h

//exampleView.h
#import <UIKit/UIKit.h>
#import "exampleViewController.h"

@interface exampleView : UIView

- (id)initWithFrame:(CGRect)frame andVC:(exampleViewController *)VC;

- (void) updateLabelText:(NSString *)newText;

@end

exampleView.m

//exampleView.m
#import "ExampleView.h"
#import "ExampleViewController.h"

@interface exampleView ()

@property (nonatomic) UILabel *label;
@property (nonatomic) UIButton *button;
@property (nonatomic) exampleViewController* VC;

@end

@implementation exampleView
// use your imagination...
@end

控制器:

//exampleViewController.h
#import <UIKit/UIKit.h>
#import "ExampleModel.h"
#import "ExampleRootView.h"

@interface ExampleViewController : UIViewController

- (id) initWithView:(exampleView *)view andModel:(ExampleModel*)model;

- (void) userActionButtonTapped();

@end

型号

//exampleModel.h
#import "exampleViewController.h"
@interface exampleModel : NSObject
-(id)initWithVC:(UIViewController *)VC;
//other model type stuff

@end

现在,当尝试初始化这些对象时,麻烦就来了。因为它们是循环依赖的,所以有点像鸡和蛋的场景。

【问题讨论】:

    标签: ios cocoa testing model-view-controller tdd


    【解决方案1】:

    设计 MVC 系统的正常方式是让事物“向下”或“横向”依赖(例如,视图依赖于控制器,控制器依赖于模型,模型仅依赖于其他模型)。这在 Apple 框架中的视图控制器中有些糊涂,但仍然广泛适用。让模型依赖于控制器在这里很奇怪——为什么有必要这样做?听起来可能有一些不必要的耦合。

    【讨论】:

    • 可以,但我不能牺牲在测试期间在 VC 中模拟视图和在模型中模拟 VC 的能力。
    • @BKTurley:我不确定我是否跟随。如果您的模型不依赖于 VC,则您不需要模拟它的能力。在模型中模拟 VC 的必要性是那里的耦合效应。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    • 2015-10-13
    • 2012-11-30
    • 1970-01-01
    • 2016-09-24
    • 2020-01-29
    相关资源
    最近更新 更多